var query =来自DataContext.Employees中的e 在DataContext.Dept中加入d 在e.DeptId等于d.Id 在DataContext.OtherInfo中加入o 在e.Id等于o.EmployeeId 其中e.EmployeeId == 4 选择新的Employee_Dept // DTO { EmployeeName = e.Name, DEPTNAME = d.Name 雇员= e.ID DEPTID = d.Id ContactNo = o.ContactNo }
我想用Lambda表达式编写它,这可以写 -
var query = DataContext.Employees.Join(Dept,e=>e.DeptId,d=>d.Id,(e,d)).Where(e=>e.EmployeeId=4)
任何人都可以帮我完成此查询。谢谢你的帮助。
答案 0 :(得分:6)
我同意Craig Stuntz对Join的错误使用,但您可以通过以下方式使用扩展方法表达相同的LINQ查询:
return DataContext.Employees
.Join(DataContext.Dept, e => e.DeptId, d => d.Id, (e,d) => new { Employee = e, Department = d })
.Join(DataContext.OtherInfo, s => s.Employee.Id, o => o.EmployeeId, (s, o) => new { Employee => s.Employee, Department = s.Department, OtherInfo = o })
.Where(e => e.Employee.Id == 4)
.Select(e => select new Employee_Dept//DTO
{
EmployeeName=e.Employee.Name,
DeptName=e.Department.Name
EmployeeId=e.Employee.ID
DeptId=e.Department.Id
ContactNo=e.OtherInfo.ContactNo
}
答案 1 :(得分:4)
It's usually wrong to use join
in LINQ to SQL。只需写下:
var query=from e in DataContext.Employees
where e.EmployeeId==4
select new Employee_Dept//DTO
{
EmployeeName=e.Name,
DeptName=d.Dept.Name
EmployeeId=e.ID
DeptId=d.Dept.Id
}