C#实体框架递归层次结构查询 [英] C# Entity Framework recursive hierarchy query

查看:50
本文介绍了C#实体框架递归层次结构查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了说明这个问题,我将首先展示我的情况-我在SQL Server中创建了一个角色和任务架构,如下所示:

I'll first show my case in order to explain the question - I created a role and tasks architecture in SQL Server that looks like this:

我有2个主表, Roles Tasks ,以及2个链接表.

I have 2 main tables, Roles and Tasks, and 2 link tables.

我已经使用C#在Entity Framework类中生成了该模型(使用Entity Framework生成器),并且得到了这些类:

I have generated this model (using Entity Framework generator) to Entity Framework classes in C# and I got those classes:

public class Task
{
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Role> Roles { get; set; }
    public virtual ICollection<Task> ChildTask { get; set; }
    public virtual ICollection<Task> ParentTask { get; set; }
}

public class Role
{
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Task> Tasks { get; set; }
}

现在,我想获得一个角色的所有任务名称,但由于任务具有自我层次结构,我遇到了麻烦.

Now I want to get all the tasks names of one role and I'm having trouble because task has self hierarchy.

我可以使用实体框架来执行此操作,而无需手动遍历每个子级/SQL Server存储过程吗?

Can I do it using entity framework and without go over each child manually/SQL Server stored procedure?

谢谢.

推荐答案

您可以在 LazyLoading 的帮助下以递归方式进行操作:

You can do it recursively with the help of LazyLoading:

public List<string> GetTaskNames(Task task, List<string> tasks = null)
{
    if(tasks == null);
        tasks = new List<string>();
    tasks.Add(task.Name);

    foreach(var child in task.ChildTask)
       GetTaskNames(child, tasks);

    return tasks;
}

var role = context.Roles.Find(roleId);
var names = role.Tasks.SelectMany(x => GetTaskNames(x)).Distinct().ToList();

这篇关于C#实体框架递归层次结构查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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