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

前端 未结 2 522
花落未央
花落未央 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: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 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.

提交回复
热议问题