用于连接三个表的Lambda表达式

时间:2015-01-13 06:04:34

标签: c# linq linq-to-sql

员工表

EmpID
Emp_First_Name
Manager_ID
Department_ID
RoleID

部门表

Department_ID
Department_N

AME

角色表

RoleID
RoleName

加入三个表

var join = from u in db.TBL_Employees
                       join v in db.TBL_Departments
                       on u.Department_ID equals v.Department_ID
                       join x in db.TBL_Employees
                       on u.Manager_ID equals x.Emp_ID
                       join z in db.TBL_Roles
                       on u.RoleID equals z.RoleID
                       select new
                       {
                           Name = u.Emp_First_Name,
                           Department = v.Department_Name,
                           Manager = x.Emp_First_Name,
                           Role = z.RoleName
                       };

此查询工作正常。 但我想在Lambda Expression中编写相同的查询。 如何使用Lambda Expression显示相同的输出?

1 个答案:

答案 0 :(得分:1)

你可以作为Joins的连续执行此操作,每个都继续使用新连接进行前面的投影,但正如评论中所提到的,这很快变得混乱且难以遵循:(特别是如果您习惯于使用Sql连接语法)

var result = db.TBL_Employees
   .Join(db.TBL_Departments, u => u.Department_ID, v => v.Department_ID, 
         (u, v) => new {Employee = u, Department = v})
   .Join(db.TBL_Employees, ed => ed.Employee.Manager_ID, x => x.Emp_ID, 
         (ed, x) => new {EmployeeDepartment = ed, Manager = x})
   .Join(db.TBL_Roles, edm => edm.EmployeeDepartment.Employee.RoleID, z => z.RoleID, 
         (edm, z) => new {EmployeeDepartmentManager = edm, Role = z})
.Select(edmr => new
{
  Name = edmr.EmployeeDepartmentManager.EmployeeDepartment.Employee.Emp_First_Name,
  Department = edmr.EmployeeDepartmentManager.EmployeeDepartment.Department.Department_Name,
  Manager = edmr.EmployeeDepartmentManager.Manager.Emp_First_Name,
  Role = edmr.Role.RoleName
});

(我保留了原始别名的可追溯性,并使用您的模式为中间匿名投影添加了新的别名,例如edmrEmployeeDepartmentManagerRole

但是,我建议您确保强制执行表中似乎存在的外键关系,然后将它们作为Linq2Sql DBML模型中的可导航关系。启用延迟加载或设置适当的预先加载LoadsWith DataContext options后,您就可以将查询和投影简化为:

var result = db.TBL_Employees
   .Select(e => new
{      
    Name = e.Emp_First_Name,
    Department = e.Department.Department_Name,
    Manager = e.Manager.Emp_First_Name,
    Role = e.Role.RoleName
});