我有一个典型的员工经理关系表如下:
CREATE TABLE [dbo].[Employees]
(
[EmpNum] [int] NOT NULL,
[FirstName] [varchar](25) NOT NULL,
[LastName] [varchar](40) NOT NULL,
[PositionTitle] [varchar](60) NOT NULL,
[MgrEmpNum] [int] NOT NULL,
)
在SQL Server中使用CTE,我可以获取特定经理以及向他们报告的所有员工的数据以及该级别。
我正在使用存储过程来执行CTE并使用Entity Framework中的相同SP来获取数据。
将此数据填充到以下类中的最佳方法是什么:
public class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Title { get; set; }
public List<Employee> Subordinates { get; set; }
public int Level { get; set; }
public int ManagerNumber { get; set; }
}
因此,经理将是唯一的对象,他们所有的直接下属都应该在下属中。每个下属同样可以让其他员工向他们报告。无论方法如何,我都需要模型中的数据,如上所述。
答案 0 :(得分:0)
这是伪代码,因为我不经常编写C#来了解内存中的语法:
MgrId = {the EmpNum of the Manager you want to populate the class for}
{Execute SQL command to call CTE that gets a particular manager and all subordinates with Level}
{Populate a DataTable with the results of the SQL Command}
foreach row in TheDataTable
{
if EmpNum = MgrId 'this is the manager
{set the names and EmpNums of the class with the columns from this row}
else 'this is a subordinate
{add the EmpNum or Name (whichever you want) to the Employee <List> property of the class}
}
答案 1 :(得分:0)
这就是我所做的:
将数据库中的数据填充到:
List<Employee> employeeFromDb;
创建了一个存储顶级经理的对象:
var manager = query.First(h => h.Level == 0);
AddSubordinate(manager);
然后以递归方式调用以下方法:
private void AddSubordinate(Employee parentEmployee)
{
var subs = employeeFromDb.Where(m => m.ManagerNumber == parentEmployee.EmployeeNumber).ToList();
employeeFromDb.Remove(parentEmployee);
if (subs.Count != 0)
parentEmployee.Subordinates = new List<Employee>(subs);
if (employeeFromDb.Count == 0)
return;
AddSubordinate(employeeFromDb.First());
}