2010-04-29 118 views
4

我的實體模型如下: Person,Store和PersonStores多對多的子表存儲PeronId,StoreId 當我得到一個人,如下面的代碼,並嘗試刪除所有StoreLocations,它將從PersonStores中刪除它們,但也會將其從Store Table中刪除,這是不可取的。 另外,如果我有另一個人具有相同的商店Id,那麼它不會說 "The DELETE statement conflicted with the REFERENCE constraint \"FK_PersonStores_StoreLocations\". The conflict occurred in database \"EFMapping2\", table \"dbo.PersonStores\", column 'StoreId'.\r\nThe statement has been terminated",因爲它試圖刪除StoreId,但StoreId用於另一個PeronId,因此拋出異常。EF 4.0 - 多對多關係 - 刪除問題

Person p = null; 
     using (ClassLibrary1.Entities context = new ClassLibrary1.Entities()) 
     { 
      p = context.People.Where(x=> x.PersonId == 11).FirstOrDefault(); 
      List<StoreLocation> locations = p.StoreLocations.ToList(); 
      foreach (var item in locations) 
      { 
       context.Attach(item); 
       context.DeleteObject(item); 
       context.SaveChanges(); 
      } 
     } 

回答

10

的問題是,你實際上並不希望刪除的商店本身,只是店裏和人之間的關係。嘗試這樣的代替:

Person p = null; 
using (ClassLibrary1.Entities context = new ClassLibrary1.Entities()) 
{ 
    p = context.People.Where(x=> x.PersonId == 11).FirstOrDefault(); 
    p.StoreLocations.Clear(); 
    context.SaveChanges(); 
} 

這將讓你的人,從他的商店列表中刪除所有商店,並保存更改。請注意,您可能需要在using塊的第一行包含語句,具體取決於您的ObjectContext的配置方式。

+0

似乎解決了問題! – chugh97 2010-04-29 15:06:46

+0

也謝謝你!我努力解決這個問題.Clear解決了這個問題。 – willem 2011-04-09 16:21:21