开发者

How to Join in LINQ using Lambda expressions and get the result in DTO?

开发者 https://www.devze.com 2023-01-04 01:12 出处:网络
var query=from e in DataContext.Employees join d in DataContext.Dept on e.DeptIdequals d.Id join o in DataContext.OtherInfo

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 { 开发者_如何学JAVA 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.


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
          }


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

精彩评论

暂无评论...
验证码 换一张
取 消