07操作数据
1 生成DataContext文件
使用SqlMetal 工具。
sqlmetal /code:"c:\linqtest6\northwind.cs" /language:csharp "C:\linqtest6\northwnd.mdf" /pluralize
注意:pluralize表示使用英语规则自动将类别和成员名称复数化或单数化。
2 建立项目
建立控制台LinqDataManipulationApp
3 添加DLL和Namespace
添加System.Data.Linq.dll
using System.Data.Linq;
using System.Data.Linq.Mapping;
4 将northwind代码文件添加到项目
northwind.cs添加到LinqDataManipulationApp
5 添加新实体
添加一个Customer
// 创建一个新的Customer实例
Customer newCust = new Customer();
newCust.CompanyName = "AdventureWorks Cafe";
newCust.CustomerID = "ADVCA";
// 添加到customers表中
db.Customers.InsertOnSubmit(newCust);
// 提交到数据库
db.SubmitChanges();
Console.WriteLine("\nCustomers matching CA before insert");
foreach (var c in db.Customers.Where(cust => cust.CustomerID.Contains("CA")))
{
Console.WriteLine("{0}, {1}, {2}",
c.CustomerID, c.CompanyName, c.Orders.Count);
}
6 修改实体
修改Customer
// 从数据库中取一条数据
var existingCust =
(from c in db.Customers
where c.CustomerID == "ALFKI"
select c)
.First();
// 修改ContactName字段的值
existingCust.ContactName = "New Contact";
// 提交到数据库
db.SubmitChanges();
Console.WriteLine("update ok");
7 删除实体
删除订单明细
// 订单头
Order ord0 = existingCust.Orders[0];
// 订单明细
OrderDetail detail0 = ord0.OrderDetails[0];
// 显示要删除的数据
Console.WriteLine
("The Order Detail to be deleted is: OrderID = {0}, ProductID = {1}",
detail0.OrderID, detail0.ProductID);
// 数据行标记为删除
db.OrderDetails.DeleteOnSubmit(detail0);
// 提交到数据库
db.SubmitChanges();
注意:调用SubmitChanges后才写到数据库。
人的一生应该这样度过:当他回首往事的时候,不会因为虚度年华而悔恨,也不会因为碌碌无为而羞愧。
浙公网安备 33010602011771号