How can I recursively retrieve a hierarchy of records using EF Core?

只愿长相守 提交于 2021-01-29 08:33:17

问题


I am using EF Core 2.1. I have a Group object that has the following properties:

  • int GroupId
  • int? ParentGroupId
  • Group ParentGroup

The object references the GroupId of its parent using the ParentGroupId property. The depth of the hierarchy is not known when querying. How can I retrieve the entire hierarchy?

I've tried the following, which will get me three levels deep, but how can I get all levels of the hierarchy without knowing the depth? Do I need to rely on a stored proc?

var group = await _membershipDbContext.Groups
    .Include(g => g.ParentGroup)
        .ThenInclude(g => g.ParentGroup)
    .SingleOrDefaultAsync(g => g.GroupId == id);

回答1:


You have three options:

  1. Use lazy loading. This way every time you'll access the parent group, it will automatically loaded from the database.
  2. Use explicit loading for recursively load the parent groups (see explicit loading)
  3. Create a view or stored procedure in the database that will return all the data you need and then create the object graph manually.

Which method is right for you depends on your unique use-case and the amount of data to load. Options 1 and 2 are not that different from each other, but with option 2 you control when the objects are loaded. Option 3 will probably be the most efficient, but might pose problems when saving back changes (as you transform the object graph manually).



来源:https://stackoverflow.com/questions/58399774/how-can-i-recursively-retrieve-a-hierarchy-of-records-using-ef-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!