我的实体模型如下: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,因此抛出异常.
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();
}
}
Run Code Online (Sandbox Code Playgroud)