我的实体模型如下: 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();
}
}
似乎解决了问题! – chugh97 2010-04-29 15:06:46
也谢谢你!我努力解决这个问题.Clear解决了这个问题。 – willem 2011-04-09 16:21:21