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
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.