C# Entity Framework recursive hierarchy query

馋奶兔 提交于 2019-12-24 11:46:05

问题


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:

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

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.

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

Thanks.


回答1:


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();


来源:https://stackoverflow.com/questions/52138605/c-sharp-entity-framework-recursive-hierarchy-query

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