我有一个树状视图,它包含带有父项(管理器)和子项(记者)的层次结构。我需要使用LINQ从父节点到子节点获取具有不同嵌套级别的所有子项。
有我的层次树节点模型:
public class EmployeeTree
{
public EmployeeTree()
{
Reporters = new List<EmployeeTree>();
}
public int Id { get; set; }
public int? ManagerId { get; set; }
[Required]
[MaxLength(30)]
public string FirstName { get; set; }
[Required]
[MaxLength(30)]
public string SecondName { get; set; }
[Required]
[MaxLength(30)]
public string Position { get; set; }
public string Phone { get; set; }
public virtual EmployeeTree Manager { get; set; }
public virtual ICollection<EmployeeTree> Reporters { get; set; }
}
首先,我得到了父项:
public EmployeeTree GetEmployeeParent()
{
var employee = context.Employees
.Where(x => x.ManagerId == null)
.FirstOrDefault();
GetEmployeeChildTree(employee);
return employee;
}
然后,我尝试通过递归获取所有子元素,但是我有NullReferenceException原因,我没有得到子项。
private void GetEmployeeChildTree(EmployeeTree employee)
{
var employeeReporters = context.Employees
.Include(x => x.Reporters)
.Where(x => x.ManagerId == employee.Id).ToList();
if (employeeReporters.Count() > 0)
{
foreach (var reportersNode in employeeReporters)
{
GetEmployeeChildTree(reportersNode);
employee.Reporters.Add(reportersNode);
}
}
}
据我了解,我需要使用递归来获取所有级别的子项。感谢您的任何建议。