且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

实体框架不想删除表中具有多对多关系的行

更新时间:2022-11-05 08:59:58

using (var db = new FIXEntities())
{
   db.Database.Log = x => Debug.WriteLine(x);
   var organizationDto = db.Organizations.First();
   var contactDto = organizationDto.Contacts.Last();
   //organizationDto.Contacts.Remove(contactDto); // not necessary

   db.Entry(contactDto).State = EntityState.Deleted;
   // or, like this if you prefer
   db.Set<OrganizationContact>().Remove(contactDto);

   db.SaveChanges();
}

仅从收集属性中删除它是不够的,您必须删除它。由于多对多拥有自己的主键,因此EF并不知道您要删除它,而是认为您希望将其取消关联。因此,您必须删除它才能满足EF在异常情况下抱怨的FK关系。

It is not enough to just remove it from the collection property, you have to delete it. Since your many-to-many has its own primary key, EF doesn't know that you want it deleted, it just thinks you want it disassociated. So you have to delete it in order to satisfy the FK relationship that EF is complaining about in the exception.