Linq中的SQL Query内连接

时间:2015-11-03 15:45:58

标签: linq

SELECT  
    EmployeeType.EmployeeTypeName, EmployeeAttendanceTypes.OverTimeAllowed, 
    EmployeeAttendanceTypes.SundayOffAllowed,                 
    EmployeeAttendanceTypes.LeavesAllowed
FROM
    EmployeeAttendanceTypes 
INNER JOIN
    EmployeeType ON EmployeeAttendanceTypes.CompanyId = EmployeeType.CompanyId 
                 AND EmployeeAttendanceTypes.EmployeeTypeId = EmployeeType.EmployeeTypeId

如何在Linq for C#中编写此查询?

1 个答案:

答案 0 :(得分:0)

我同意你不会发表的评论,但并不总是可以避免。尝试:

var result = from eat in EmployeeAttaendanceType
             join et in EmployeeType on 
                 new { cId = eat.CompanyId, etId = eat.EmployeeTypeId } 
             equals 
                 new { cId = et.CompanyId, etId = et.EmployeeTypeId }
             select new {
                 EmployeeTypeName = EmployeeType.EmployeeTypeName, 
                 OverTimeAllowed = EmployeeAttendanceTypes.OverTimeAllowed,     
                 SundayOffAllowed = EmployeeAttendanceTypes.SundayOffAllowed,                 
                 LeavesAllowed = EmployeeAttendanceTypes.LeavesAllowed
             }

或者你可以这样做

var result = EmployeeAttendanceType.Join(EmployeeType,
               eat => new { cId = eat.CompanyId, etId = eat.EmployeeTypeId },        
               et => new { cId = et.CompanyId, etId = et.EmployeeTypeId },
               (eat, et) => new {
                   EmployeeTypeName = EmployeeType.EmployeeTypeName, 
                   OverTimeAllowed = EmployeeAttendanceTypes.OverTimeAllowed,     
                   SundayOffAllowed = EmployeeAttendanceTypes.SundayOffAllowed,                 
                   LeavesAllowed = EmployeeAttendanceTypes.LeavesAllowed
               });

这些选择为匿名类型,但可以选择任何对象。