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

前端 未结 20 1034
情书的邮戳
情书的邮戳 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:21

    This happens because the Child Entity is marked as Modified instead of Deleted.

    And the modification that EF does to the Child Entity when parent.Remove(child) is executed, is simply setting the reference to its parent to null.

    You can check the child's EntityState by typing the following code into Visual Studio's Immediate Window when the exception occurs, after executing SaveChanges():

    _context.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Modified).ElementAt(X).Entity
    

    where X should be replaced by the deleted Entity.

    If you don't have access to the ObjectContext to execute _context.ChildEntity.Remove(child), you can solve this issue by making the foreign key a part of the primary key on the child table.

    Parent
     ________________
    | PK    IdParent |
    |       Name     |
    |________________|
    
    Child
     ________________
    | PK    IdChild  |
    | PK,FK IdParent |
    |       Name     |
    |________________|
    

    This way, if you execute parent.Remove(child), EF will correctly mark the Entity as Deleted.

提交回复
热议问题