Is it possible to enable relationship fixup when change tracking is disabled but proxies are generated

纵饮孤独 提交于 2019-12-10 17:56:41

问题


I have entities which form a tree relationships.

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

    public int ParentId {get;set;}
    public virtual MyEntity Parent {get;set;}

    public virtual ICollection<MyEntity> Children {get;set;}
}

When these entities are called without AsNoTracking() relationships are fixed up.

var entities = MyEntitiesSet.ToList();

All navigation properties and collections are set.
However if AsNoTracking() is called:

var entities = MyEntitiesSet.AsNoTracking.ToList();

no navigation property is set. This is understandable. But I cannot understand why collection and naviagtion properties are not overriden to provide relationship fixup for this code:

entity.Parent = anotherEntity;

Here I expect that anotherEntity.Children collection now contains entity. Alas, this is false expectation as my experimetns show.

Is it possible to get desired behavior without enabling change tracking?

Update 1

I loked at generated proxies and noted that overriden collections are hashsets of the proxy type. They are not backed up by EntityCollection<TEntity> what was true to EF 4 ObjectContext proxies.

And I've found the answer here.
DbContext does not generate proxies which fix up relationships.


回答1:


DbContext does not generate proxies which fix up relationships.

Proof is here: http://connect.microsoft.com/VisualStudio/feedback/details/760609/poco-navigation-proxies-should-fixup-the-other-end-automatically

Yet, when entitties are attached to the context loading related entities:

context.ASet.ToList();
context.BSet.ToList();

sets relationships automatically.




回答2:


i arent sure how this has anything to do with tracking, however to get the relationship working you need to associate the collection navigation property with the key it is using. See here for an example.



来源:https://stackoverflow.com/questions/18255157/is-it-possible-to-enable-relationship-fixup-when-change-tracking-is-disabled-but

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