Why does Setting EntityState to Detached Empty a Property of type List?

前端 未结 1 680
眼角桃花
眼角桃花 2021-01-02 07:59

Using Entity Framework Code First, I have something like:

public class Foo
{
    public int Id { get; set; }

    public List Bars { get; set; }
}         


        
相关标签:
1条回答
  • 2021-01-02 08:53

    The reason why the list is emptied is a combination of two rules in Entity Framework:

    1. When you detach an object only this object itself is detached without the objects any navigation properties refer to.

    2. The ObjectContext/DbContext does not allow to hold an object graph which is partially attached to the context and partially detached. Although this can happen as a temporary state when using POCOs EF will always fix this temporary state by automatically attaching detached objects in the graph inside of various methods (like Add, Attach, setting the state of an entity, etc.) or latest when SaveChanges is called.

    This means that when you detach the root object from the context, EF will clear the list of children because: a) the children stay attached (rule 1) and b) a mix of detached and attached objects in the graph is not allowed (rule 2).

    As far as I can tell there is no way to detach an object graph from the context while maintaining the original tree structure. You can detach the parent and then the children one after each other. As a result you have detached all objects of the tree from the context but the tree is destroyed at the same time - each navigation property is nullified.

    The main purpose of detaching entities manually is to release them for garbage collection in situations where you have memory resource limitations and don't want and need to hold a huge amount of objects in the context. For this purpose it doesn't matter that the graph structure is destroyed.

    I don't know why you need to detach objects from the context. But keep in mind that there is also the option to load entities from the database without attaching them to the context in the first place, like using AsNoTracking().

    Another answer about the problem with some references to MSDN documentation is here: https://stackoverflow.com/a/7693732/270591

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