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