问题
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