Deleting in EF Code first causes navigational properties to be set to null and empty

别说谁变了你拦得住时间么 提交于 2019-12-01 18:49:09

This is how EF works. The problem is that your Playlist forms entity graph with other relations and EF uses very simple rule for tracking entity graphs: All entities in the graph must be tracked - there cannot be reference to entity which is not tracked. I don't give you reference to description of this rule, it is just my observation but I didn't find any single exception to this rule.

Edit: Updated version - I just checked internal implementation and relations are indeed nulled during calling Delete

So what happened in your code.

  • You marked your Playlist as deleted
  • EF passes delete operation to the state manager which does the fixup - it will null all relations
  • You saved changes to the database
  • Because there are no cascade deletes from Playlist all related objects remain undeleted
  • Once you saved changes EF internally accepted them and set change tracker to current state
  • Because the current state of Playlist is non existing (deleted in the database) it was detached from the context
  • Detaching has broken entity graph and EF fixed it by modifying navigation properties on both ends

The code responsible for nulling from System.Data.Objects.EntityEntry.Delete(doFixup) (doFixup is true) - the class is internal:

if (doFixup && (base.State != EntityState.Deleted))
{
    this.RelationshipManager.NullAllFKsInDependentsForWhichThisIsThePrincipal();
    this.NullAllForeignKeys();
    this.FixupRelationships();
}

In your scenario this should have simple workaround - create DTO before you delete entity.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!