loading a full hierarchy from a self referencing table with EntityFramework.Core
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.