C# Entity Framework recursive hierarchy query

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

Question

In order to answer the topic, I'll first demonstrate my situation. I built the following role and task architecture in SQL Server:

enter image description here

My two major tables areRoles and Tasks two link tables, and.

Using the Entity Framework generator, I converted this model into Entity Framework classes in C# and obtained the following 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 that tasks have self-hierarchies, I'm having difficulties getting the names of all the tasks in a single role.

Can I accomplish it without manually going through each kid or utilising a SQL Server stored procedure and entity framework?

Thanks.

1
1
9/2/2018 3:59:36 PM

Popular Answer

With the use of recursion, you mayLazyLoading :

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