LINQ to SQL刪除實(shí)現(xiàn)淺析
我們?cè)趯W(xué)習(xí)了LINQ to SQL之查詢以及添加和更新的實(shí)現(xiàn)之后,現(xiàn)在我們來(lái)看看,LINQ to SQL是如何怎樣進(jìn)行刪除數(shù)據(jù)的,具體的實(shí)現(xiàn)過(guò)程和步驟是什么呢?讓我們來(lái)看看。
LINQ to SQL刪除數(shù)據(jù)以Northwind為例子:
1、首先以Customers表的一行數(shù)據(jù)為例,來(lái)實(shí)現(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、通過(guò)查看數(shù)據(jù)庫(kù)中的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ù)庫(kù)中查詢?cè)摋l數(shù)據(jù),理論上來(lái)說(shuō)數(shù)據(jù)庫(kù)中該數(shù)據(jù)已經(jīng)不存在了,查詢出來(lái)應(yīng)該沒有結(jié)果??墒瞧聊惠敵鰹?TEST1",這是已經(jīng)被刪除的Customer的CustomerID。是不是會(huì)讓人覺得奇怪,數(shù)據(jù)庫(kù)中數(shù)據(jù)已經(jīng)不存在了,但是查詢還是可以得到正確的結(jié)果。其實(shí)原因也很簡(jiǎn)單,雖然在數(shù)據(jù)庫(kù)中該數(shù)據(jù)已經(jīng)被刪除,但是在DataContext中的Identity Cache還保存著對(duì)該對(duì)象的引用(什么是Identity Cache,前文已經(jīng)解釋過(guò)了),查詢出來(lái)的結(jié)果是在DataContext中Cache著的對(duì)象而不是存在于數(shù)據(jù)庫(kù)中的。可以知道如果在另一個(gè)DataContext中查詢?cè)摂?shù)據(jù),肯定是查詢不到的。
3、LINQ to SQL刪除中的級(jí)聯(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í)行這段代碼,通過(guò)SQL Profile可以發(fā)現(xiàn),并沒有運(yùn)行delete from Orders...的SQL語(yǔ)句而是update,只是把Orders表中那條記錄的CustomerID設(shè)置為NULL,刪除的是該記錄與Customer的關(guān)系而并沒有真正刪除這條記錄。要想真正刪除該記錄必須通過(guò)DataContext來(lái)操作:
- ctx.Orders.Remove(order1);
- ctx.SubmitChanges();
這是在刪除過(guò)程中值得注意的一個(gè)問題。
要?jiǎng)h除Customer以及相關(guān)的Order應(yīng)該這樣來(lái)操作(也可以在數(shù)據(jù)庫(kù)中設(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í)也會(huì)遇到像數(shù)據(jù)更新一樣的沖突問題,解決方法基本相同這里就不多說(shuō)了。
原文來(lái)自博客園:http://www.cnblogs.com/blusehuang/archive/2007/07/08/810485.html
關(guān)于LINQ to SQL刪除實(shí)現(xiàn)問題就向你介紹到這里,希望對(duì)你了解和學(xué)習(xí)實(shí)現(xiàn)LINQ to SQL刪除有所幫助。
【編輯推薦】


















