C# Entity Framework recursive hierarchy query

c# entity-framework entity-framework-6 sql-server

Question

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:

enter image description here

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
1
9/2/2018 3:59:36 PM

Popular Answer

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();
0
9/3/2018 6:26:26 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow