Explanation why this question is different to: EF - multiple includes to eager load hierarchical data. Bad practice?
I have built stored procedure to get all childs in all levels using recursive cte stored procedure to get all childs ids of any level of self-referencing table using Entity Framework and recursive cte
In fact loading the whole hierarchy is quite easy thanks to the so called EF (Core) relationship fixup.
Let say we have the following model:
public class Hierarchy
{
public int Id { get; set; }
public string Name { get; set; }
public Hierarchy Parent { get; set; }
public ICollection<Hierarchy> Children { get; set; }
}
Then the following code
var hierarchy = db.Hierarchy.Include(e => e.Children).ToList();
will load the whole hierarchy with correctly populated Parent
and Children
properties.
The problem described in the referenced posts arise when you need to load just part of the hierarchy, which is hard due to the lack of CTE like support in LINQ.