The relationship could not be changed because one or more of the foreign-key properties is non-nullable

前端 未结 20 1071
情书的邮戳
情书的邮戳 2020-11-22 04:44

I am getting this error when I GetById() on an entity and then set the collection of child entities to my new list which comes from the MVC view.

The

20条回答
  •  鱼传尺愫
    2020-11-22 05:32

    I had same problem, but I knew it had worked OK in other cases, so I reduced the problem to this:

    parent.OtherRelatedItems.Clear();  //this worked OK on SaveChanges() - items were being deleted from DB
    parent.ProblematicItems.Clear();   // this was causing the mentioned exception on SaveChanges()
    
    • OtherRelatedItems had a composite Primary Key (parentId + some local column) and worked OK
    • ProblematicItems had their own single-column Primary Key, and the parentId was only a FK. This was causing the exception after Clear().

    All I had to do was to make the ParentId a part of composite PK to indicate that the children can't exist without a parent. I used DB-first model, added the PK and marked the parentId column as EntityKey (so, I had to update it both in DB and EF - not sure if EF alone would be enough).

    Once you think about it, it's a very elegant distinction that EF uses to decide if children "make sense" without a parent (in this case Clear() won't delete them and throw exception unless you set the ParentId to something else/special), or - like in the original question - we expect the items to be deleted once they are removed from the parent.

提交回复
热议问题