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

前端 未结 1 1877
被撕碎了的回忆
被撕碎了的回忆 2021-01-19 16:28

I noticed something interesting when I was performing a delete using EF code first. I use the following domain model:

public class User
{
    public virtual          


        
相关标签:
1条回答
  • 2021-01-19 16:56

    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.

    0 讨论(0)
提交回复
热议问题