tags:

views:

54

answers:

2

Hi I have a query as -

var query=from e in DataContext.Employees
          join d in DataContext.Dept
          on e.DeptId  equals d.Id
          join o in DataContext.OtherInfo
          on e.Id equals o.EmployeeId 
          where e.EmployeeId==4 
          select new Employee_Dept//DTO
          {
              EmployeeName=e.Name,
              DeptName=d.Name
              EmployeeId=e.ID
              DeptId=d.Id
              ContactNo=o.ContactNo
          }

I want to write it using Lambda expressions this is could write -

var query = DataContext.Employees.Join(Dept,e=>e.DeptId,d=>d.Id,(e,d)).Where(e=>e.EmployeeId=4)

can anyone help me complete this query. Thanks for your help.

+2  A: 

It's usually wrong to use join in LINQ to SQL. Just write:

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
          }
Craig Stuntz
I would agree that using join decreases readability, but your rewrite makes an assumption that isn't evident in the original question: that there exists an association between an employee and their department (i.e. the Dept property on Employee you reference)
Rich
@Rich, as that's the default behavior of L2S, I don't think that's such a big assumption.
Craig Stuntz
+2  A: 

I agree with Craig Stuntz that it is wrong usage of Join, but you can express the same LINQ query using extension methods in following way:

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
          }
STO