2010-04-29 119 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