日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
LINQtoSQL刪除實現(xiàn)淺析

我們在學(xué)習(xí)了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刪除:

 
 
 
  1. NorthwindDataContext ctx = new NorthwindDataContext();
  2. Customer test1 = ctx.Customers.Single(c => c.CustomerID == "TEST1");
  3. ctx.Customers.Remove(test1);
  4. ctx.SubmitChanges();

2、通過查看數(shù)據(jù)庫中的Customers表,可以發(fā)現(xiàn)該條數(shù)據(jù)已經(jīng)被刪除了。

 
 
 
  1. NorthwindDataContext ctx = new NorthwindDataContext();
  2. Customer test1 = ctx.Customers.Single(c => c.CustomerID == "TEST1");
  3. ctx.Customers.Remove(test1);
  4. ctx.SubmitChanges();
  5. test1 = ctx.Customers.Single(c => c.CustomerID == "TEST1");
  6. Console.WriteLine(test1.CustomerID);

先刪除CustomerID為"TEST1"的一行數(shù)據(jù),然后再在數(shù)據(jù)庫中查詢該條數(shù)據(jù),理論上來說數(shù)據(jù)庫中該數(shù)據(jù)已經(jīng)不存在了,查詢出來應(yī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、LINQto SQL刪除中的級聯(lián)刪除,以Customers和Orders為例:

 
 
 
  1. NorthwindDataContext ctx = new NorthwindDataContext();
  2. Customer test1 = ctx.Customers.Single(c => c.CustomerID == "TEST1");
  3. Order order1 = test1.Orders.Single(o => o.ShipCity == "Shanghai");
  4. test1.Orders.Remove(order1);
  5. ctx.SubmitChanges();

在該示例中,欲刪除CustomerID為"TEST1"的Customer的訂單中ShipCity為上海的訂單。執(zhí)行這段代碼,通過SQL Profile可以發(fā)現(xiàn),并沒有運行delete from Orders...的SQL語句而是update,只是把Orders表中那條記錄的CustomerID設(shè)置為NULL,刪除的是該記錄與Customer的關(guān)系而并沒有真正刪除這條記錄。要想真正刪除該記錄必須通過DataContext來操作:

 
 
 
  1. ctx.Orders.Remove(order1);
  2. ctx.SubmitChanges();

這是在刪除過程中值得注意的一個問題。

要刪除Customer以及相關(guān)的Order應(yīng)該這樣來操作(也可以在數(shù)據(jù)庫中設(shè)置級聯(lián)刪除):

 
 
 
  1. NorthwindDataContext ctx = new NorthwindDataContext();
  2. Customer test1 = ctx.Customers.Single(c => c.CustomerID == "TEST1");
  3. foreach (Order o in test1.Orders)
  4. {
  5. test1.Orders.Remove(o);
  6. ctx.Orders.Remove(o);
  7. }
  8. ctx.Customers.Remove(test1);
  9. ctx.SubmitChanges();

在數(shù)據(jù)刪除時也會遇到像數(shù)據(jù)更新一樣的沖突問題,解決方法基本相同這里就不多說了。

原文來自博客園:http://www.cnblogs.com/blusehuang/archive/2007/07/08/810485.html

關(guān)于LINQ to SQL刪除實現(xiàn)問題就向你介紹到這里,希望對你了解和學(xué)習(xí)實現(xiàn)LINQ to SQL刪除有所幫助。


分享文章:LINQtoSQL刪除實現(xiàn)淺析
標(biāo)題網(wǎng)址:http://www.5511xx.com/article/dhhijsj.html