如何使用EF Core递归检索记录的层次结构? [英] How can I recursively retrieve a hierarchy of records using EF Core?

查看:107
本文介绍了如何使用EF Core递归检索记录的层次结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用EF Core 2.1.我有一个具有以下属性的Group对象:

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

  • int GroupId
  • int?ParentGroupId
  • 组ParentGroup

该对象使用ParentGroupId属性引用其父级的GroupId.查询时未知层次结构的深度.如何检索整个层次结构?

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?

我已经尝试了以下方法,这将使我更深入地了解三个层次,但是如何在不知道深度的情况下获得层次结构的所有层次呢?我需要依赖存储的proc吗?

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. 使用延迟加载.这样,每次您访问父组时,它将自动从数据库中加载.
  2. 使用显式加载以递归方式加载父组(请参阅哪种方法最适合您,取决于您的独特用例和要加载的数据量.选项1和2并没有什么不同,但是使用选项2可以控制何时加载对象.选项3可能是最有效的,但在保存更改(手动转换对象图时)时可能会出现问题.

    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).

    这篇关于如何使用EF Core递归检索记录的层次结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆