Search code examples
c#entity-framework-corenavigationself-join

In Entity Framework Core, how to populate self-referencing navigation collection without additional Include (using only entities already tracked)?


I have an entity called Position with foreign key to itself: int Id; and int ParentId;.This gives me two navigation properties: Position Parent; and List<Position> Children;. When I'm loading the entire table into EF context (tracked), I'd like EF to populate those properties without emitting additional SQL joins (since all participating entities are being loaded anyways). Is there any way to achieve this during query creation or later, maybe something like db.Entry(positions[0]).Collection(x => x. Children).Load();, but limited to already tracked entities?


Solution

  • If you have loaded all related positions as tracked entities then you should find that the relationships are already populated when leaving off the Include. Eager loading is generally recommended as without it EF will only populate references from the tracking cache which might be only an incomplete representation of the state. If you can safely assume that all related positions are loaded and tracked then you can ignore adding the Include. I'd probably throw a comment in there explaining that at that point all positions should have been loaded. Any optimizations or re-factoring could break your current expected behavior.