当前位置:首页 > LINQ体验(9)——LINQ to SQL语句之Insert/Update/Delete操作

LINQ体验(9)——LINQ to SQL语句之Insert/Update/Delete操作

点击次数:1275  更新日期:2010-12-29
\n

我们继续讲解LINQ语句,这篇我们来讨论Insert/Update/Delete操作。这个在我们的程序中最为常用了。我们直接看例子。


\n

Insert/Update/Delete操作


\n

Insert


\n

1.简单形式


\n

说明:new一个对象,使用InsertOnSubmit方法将其加入到对应的集合中,使用SubmitChanges()提交到数据库。

NorthwindDataContext db = new NorthwindDataContext();
\nvar newCustomer = new Customer { CustomerID = “MCSFT”,CompanyName = “Microsoft”,ContactName = “John Doe”,
\n ContactTitle = “Sales Manager”,
\n Address = “1 Microsoft Way”,City = “Redmond”,Region = “WA”,PostalCode = “98052″,
\n Country = “USA”,Phone = “(425) 555-1234″,Fax = null };
\ndb.Customers.InsertOnSubmit(newCustomer);
\ndb.SubmitChanges();

\n

2.一对多关系


\n

说明:Category与Product是一对多的关系,提交Category(一端)的数据时,LINQ to SQL会自动将Product(多端)的数据一起提交。

var newCategory = new Category { CategoryName = “Widgets”, Description = “Widgets are the customer-facing
\n analogues to sprockets and cogs.” };
\nvar newProduct = new Product { ProductName = “Blue Widget”, UnitPrice = 34.56M, Category = newCategory };
\ndb.Categories.InsertOnSubmit(newCategory);
\ndb.SubmitChanges();

\n

3.多对多关系


\n

说明:在多对多关系中,我们需要依次提交。

var newEmployee = new Employee { FirstName = “Kira”, LastName = “Smith” };
\nvar newTerritory = new Territory { TerritoryID = “12345″, TerritoryDescription = “Anytown”,
\n Region = db.Regions.First() };
\nvar newEmployeeTerritory = new EmployeeTerritory { Employee = newEmployee, Territory = newTerritory };
\ndb.Employees.InsertOnSubmit(newEmployee);
\ndb.Territories.InsertOnSubmit(newTerritory);
\ndb.EmployeeTerritories.InsertOnSubmit(newEmployeeTerritory);
\ndb.SubmitChanges();

\n

4.Override using Dynamic CUD


\n

说明:CUD就是Create、Update、Delete的缩写。下面的例子就是新建一个ID(主键)为32的Region,不考虑数据库中有没有ID为32的数据,如果有则替换原来的数据,没有则插入。(不知道这样说对不对。大家指点一下)

Region nwRegion = new Region() { RegionID = 32, RegionDescription = “Rainy” };
\ndb.Regions.InsertOnSubmit(nwRegion);
\ndb.SubmitChanges();

\n

Update


\n

说明:更新操作,先获取对象,进行修改操作之后,直接调用SubmitChanges()方法即可提交。注意,这里是在同一个DataContext中,对于不同的DataContex看下面的讲解。


\n

1.简单形式

Customer cust = db.Customers.First(c => c.CustomerID == “ALFKI”);
\ncust.ContactTitle = “Vice President”;
\ndb.SubmitChanges();

\n

2.多个项

var q = from p in db.Products
\n where p.CategoryID == 1
\n select p;
\nforeach (var p in q)
\n{
\n p.UnitPrice += 1.00M;
\n}
\ndb.SubmitChanges();

\n

Delete


\n

1.简单形式


\n

说明:调用DeleteOnSubmit方法即可。

OrderDetail orderDetail = db.OrderDetails.First(c => c.OrderID == 10255 && c.ProductID == 36);
\ndb.OrderDetails.DeleteOnSubmit(orderDetail);
\ndb.SubmitChanges();

\n

2.一对多关系


\n

说明:Order与OrderDetail是一对多关系,首先DeleteOnSubmit其OrderDetail(多端),其次DeleteOnSubmit其Order(一端)。因为一端是主键。

var orderDetails =
\n from o in db.OrderDetails
\n where o.Order.CustomerID == “WARTH” && o.Order.EmployeeID == 3
\n select o;
\nvar order =
\n (from o in db.Orders
\n where o.CustomerID == “WARTH” && o.EmployeeID == 3
\n select o).First();
\nforeach (OrderDetail od in orderDetails)
\n{
\n db.OrderDetails.DeleteOnSubmit(od);
\n}
\ndb.Orders.DeleteOnSubmit(order);
\ndb.SubmitChanges();

\n

3.Inferred Delete(推断删除)


\n

说明:Order与OrderDetail是一对多关系,在上面的例子,我们全部删除CustomerID为WARTH和EmployeeID为3 的数据,那么我们不须全部删除呢?例如Order的OrderID为10248的OrderDetail有很多,但是我们只要删除ProductID为11的OrderDetail。这时就用Remove方法。

Order order = db.Orders.First(x => x.OrderID == 10248);
\nOrderDetail od = order.OrderDetails.First(d => d.ProductID == 11);
\norder.OrderDetails.Remove(od);
\ndb.SubmitChanges();

\n

Update with Attach


\n

说明:在对于在不同的DataContext之间,使用Attach方法来更新数据。例如在一个名为tempdb的NorthwindDataContext中,查询出Customer和Order,在另一个NorthwindDataContext中,Customer的地址更新为123 First Ave,Order的CustomerID 更新为CHOPS。

Customer c1;
\nList<Order> deserializedOrders = new List<Order>();
\nCustomer deserializedC1;
\nusing (NorthwindDataContext tempdb = new NorthwindDataContext())
\n{
\n c1 = tempdb.Customers.Single(c => c.CustomerID == “ALFKI”);
\n deserializedC1 = new Customer { Address = c1.Address, City = c1.City,CompanyName=c1.CompanyName,
\n ContactName=c1.ContactName,
\n ContactTitle=c1.ContactTitle, Country=c1.Country,
\n CustomerID=c1.CustomerID, Fax=c1.Fax,
\n Phone=c1.Phone, PostalCode=c1.PostalCode, Region=c1.Region};
\n Customer tempcust = tempdb.Customers.Single(c => c.CustomerID == “ANTON”);
\n foreach (Order o in tempcust.Orders)
\n {
\n deserializedOrders.Add(new Order {CustomerID=o.CustomerID, EmployeeID=o.EmployeeID,
\n Freight=o.Freight,OrderDate=o.OrderDate,
\n OrderID=o.OrderID,RequiredDate=o.RequiredDate,
\n ShipAddress=o.ShipAddress,ShipCity=o.ShipCity,
\n ShipName=o.ShipName,ShipCountry=o.ShipCountry,
\n ShippedDate=o.ShippedDate,
\n ShipPostalCode=o.ShipPostalCode, ShipRegion=o.ShipRegion,
\n ShipVia=o.ShipVia});
\n }
\n}
\nusing (NorthwindDataContext db2 = new NorthwindDataContext())
\n{
\n //对Customer更新,不能写错
\n db2.Customers.Attach(deserializedC1);
\n deserializedC1.Address = “123 First Ave”;
\n //对Order全部更新
\n db2.Orders.AttachAll(deserializedOrders);
\n foreach (Order o in deserializedOrders)
\n {
\n o.CustomerID = “CHOPS”;
\n }
\n db2.SubmitChanges();
\n}

\n

Update and Delete with Attach


\n

说明:在不同的DataContext中,实现插入、更新、删除。看下面的一个例子:

Customer cust = null;
\nusing (NorthwindDataContext tempdb = new NorthwindDataContext())
\n{
\n cust = tempdb.Customers.First(x => x.CustomerID == “ALFKI”);
\n}
\nOrder orderA = cust.Orders.First();
\nOrder orderB = cust.Orders.First(x => x.OrderID > orderA.OrderID);
\nusing (NorthwindDataContext db2 = new NorthwindDataContext())
\n{
\n db2.Customers.Attach(cust);
\n db2.Orders.AttachAll(cust.Orders.ToList());
\n //更新Customer的Phone.
\n cust.Phone = “2345 5436″;
\n //更新OrderA的ShipCity.
\n orderA.ShipCity = “Redmond”;
\n //删除OrderB.
\n cust.Orders.Remove(orderB);
\n //添加一个新的Order到Customer中.
\n Order orderC = new Order() { ShipCity = “New York” };
\n cust.Orders.Add(orderC);
\n //提交执行
\n db2.SubmitChanges();
\n}

\n

下篇介绍乐观事务和冲突。

\n