如何使用linqc#实现自连接以获得完整的结果
本文关键字:结果 何使用 linqc# 实现 自连接 | 更新日期: 2023-09-27 18:12:13
在我的场景中,我需要显示经理id为@Id的所有员工。
层次结构类似于
Manager --- Employee
john --- smith
john --- sam
sam --- peru
sam --- karim
我首先使用linq和实体框架DB。
我需要展示给所有的员工在特定的经理让它约翰与id = 2
我应用了2个不同的查询,但结果是相同的,即它只显示第一个层次john只获得2名员工smith和sam,但sam内部的员工也必须显示不检索。
下面是我的代码:
var lstAllUser = (List<Entities.User>)Session["AllUsers"];
int pID = Convert.ToInt32(ddlSelectedValue);
//query 1 which i try first
var lstSelectedEmployees1 = lstAllUser.Where(emp => emp.ManagerId == pID)
.Select(emp => new {
EmployeeName = emp.UserDetail.Name,
ManagerName = emp.Manager.UserDetail.Name
}).ToList();
//query 2
var lstSelectedEmployees = (from employee in lstAllUser
where employee.ManagerId == pID
join e1 in lstAllUser
on employee.ManagerId equals e1.UserID
select new
{
ManagerName = e1.UserDetail.Name,
EmployeeName = employee.UserDetail.Name
}).ToList();
gvEmployeeManager.DataSource = lstSelectedEmployees;
gvEmployeeManager.DataBind();
Aspx就像;
<asp:GridView ID="gvEmployeeManager" runat="server" AutoGenerateColumns="False" GridLines="Vertical" CssClass="table table-striped">
<Columns>
<asp:BoundField DataField="EmployeeName" HeaderText="Employee" />
<asp:BoundField DataField="ManagerName" HeaderText="Manager" />
</Columns>
</asp:GridView>
需要帮助! !
假设您想收回所有向经理报告的员工,而不仅仅是直接向他们报告的员工……
我不认为这将是可能的,在LINQ一个单一的查询。如果你使用SQL Server(2005+),你可以做一个存储过程,有一个递归的公共表表达式来做到这一点(这里的好例子:http://technet.microsoft.com/en-us/library/ms186243(v=sql.105).aspx)
在c#/LINQ中,你将减少到在一个递归代码循环中进行多个查询。下面是一个例子public Dictionary<string, string> GetEmployeesAllLevels(int managerId)
{
return GetEmployeesAllLevels(managerId, null);
}
private Dictionary<string, string> GetEmployeesAllLevels(int managerId, Dictionary<string, string> existingList)
{
if (existingList == null) existingList = new Dictionary<string, string>();
var lstSelectedEmployees1 = lstAllUser.Where(emp => emp.ManagerId == managerId)
.Select(emp => new {
EmployeeName = emp.UserDetail.Name,
ManagerName = emp.Manager.UserDetail.Name,
UserId = emp.UserId
}).ToList();
foreach(var emp in lstSelectedEmployees1)
{
existingList.Add(emp.EmployeeName, emp.ManagerName);
existingList = GetEmployeesAllLevels(emp.UserId, existingList);
}
return existingList;
}