LINQ to SQL刪除實現(xiàn)淺析
我們在學習了LINQ to SQL之查詢以及添加和更新的實現(xiàn)之后,現(xiàn)在我們來看看,LINQ to SQL是如何怎樣進行刪除數(shù)據(jù)的,具體的實現(xiàn)過程和步驟是什么呢?讓我們來看看。
LINQ to SQL刪除數(shù)據(jù)以Northwind為例子:
1、首先以Customers表的一行數(shù)據(jù)為例,來實現(xiàn)LINQ to SQL刪除:
- NorthwindDataContext ctx = new NorthwindDataContext();
- Customer test1 = ctx.Customers.Single(c => c.CustomerID == "TEST1");
- ctx.Customers.Remove(test1);
- ctx.SubmitChanges();
2、通過查看數(shù)據(jù)庫中的Customers表,可以發(fā)現(xiàn)該條數(shù)據(jù)已經(jīng)被刪除了。
- NorthwindDataContext ctx = new NorthwindDataContext();
- Customer test1 = ctx.Customers.Single(c => c.CustomerID == "TEST1");
- ctx.Customers.Remove(test1);
- ctx.SubmitChanges();
- test1 = ctx.Customers.Single(c => c.CustomerID == "TEST1");
- Console.WriteLine(test1.CustomerID);
先刪除CustomerID為"TEST1"的一行數(shù)據(jù),然后再在數(shù)據(jù)庫中查詢該條數(shù)據(jù),理論上來說數(shù)據(jù)庫中該數(shù)據(jù)已經(jīng)不存在了,查詢出來應該沒有結(jié)果。可是屏幕輸出為"TEST1",這是已經(jīng)被刪除的Customer的CustomerID。是不是會讓人覺得奇怪,數(shù)據(jù)庫中數(shù)據(jù)已經(jīng)不存在了,但是查詢還是可以得到正確的結(jié)果。其實原因也很簡單,雖然在數(shù)據(jù)庫中該數(shù)據(jù)已經(jīng)被刪除,但是在DataContext中的Identity Cache還保存著對該對象的引用(什么是Identity Cache,前文已經(jīng)解釋過了),查詢出來的結(jié)果是在DataContext中Cache著的對象而不是存在于數(shù)據(jù)庫中的??梢灾廊绻诹硪粋€DataContext中查詢該數(shù)據(jù),肯定是查詢不到的。
3、LINQ to SQL刪除中的級聯(lián)刪除,以Customers和Orders為例:
- NorthwindDataContext ctx = new NorthwindDataContext();
- Customer test1 = ctx.Customers.Single(c => c.CustomerID == "TEST1");
- Order order1 = test1.Orders.Single(o => o.ShipCity == "Shanghai");
- test1.Orders.Remove(order1);
- ctx.SubmitChanges();
在該示例中,欲刪除CustomerID為"TEST1"的Customer的訂單中ShipCity為上海的訂單。執(zhí)行這段代碼,通過SQL Profile可以發(fā)現(xiàn),并沒有運行delete from Orders...的SQL語句而是update,只是把Orders表中那條記錄的CustomerID設置為NULL,刪除的是該記錄與Customer的關(guān)系而并沒有真正刪除這條記錄。要想真正刪除該記錄必須通過DataContext來操作:
- ctx.Orders.Remove(order1);
- ctx.SubmitChanges();
這是在刪除過程中值得注意的一個問題。
要刪除Customer以及相關(guān)的Order應該這樣來操作(也可以在數(shù)據(jù)庫中設置級聯(lián)刪除):
- NorthwindDataContext ctx = new NorthwindDataContext();
- Customer test1 = ctx.Customers.Single(c => c.CustomerID == "TEST1");
- foreach (Order o in test1.Orders)
- {
- test1.Orders.Remove(o);
- ctx.Orders.Remove(o);
- }
- ctx.Customers.Remove(test1);
- ctx.SubmitChanges();
在數(shù)據(jù)刪除時也會遇到像數(shù)據(jù)更新一樣的沖突問題,解決方法基本相同這里就不多說了。
原文來自博客園:http://www.cnblogs.com/blusehuang/archive/2007/07/08/810485.html
關(guān)于LINQ to SQL刪除實現(xiàn)問題就向你介紹到這里,希望對你了解和學習實現(xiàn)LINQ to SQL刪除有所幫助。
【編輯推薦】