[英]C# Entity Framework recursive hierarchy query
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: 为了说明这个问题,我将首先展示我的案例-我在SQL Server中创建了一个角色和任务架构,如下所示:
I have 2 main tables, Roles
and Tasks
, and 2 link tables. 我有2个主表,“
Roles
和Tasks
”和2个链接表。
I have generated this model (using Entity Framework generator) to Entity Framework classes in C# and I got those classes: 我已经使用C#中的Entity Framework类生成了该模型(使用Entity Framework生成器),并且得到了这些类:
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? 我可以使用实体框架执行此操作,而无需手动检查每个子级/ SQL Server存储过程吗?
Thanks. 谢谢。
You can do it recursively with the help of LazyLoading
: 您可以在
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.