loading a full hierarchy from a self referencing table with EntityFramework.Core

前端 未结 2 510
花落未央
花落未央 2020-12-01 04:43

Explanation why this question is different to: EF - multiple includes to eager load hierarchical data. Bad practice?

  1. the possible duplicate is an opinion based
相关标签:
2条回答
  • 2020-12-01 05:15

    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

    0 讨论(0)
  • 2020-12-01 05:29

    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.

    0 讨论(0)
提交回复
热议问题