LINQ:内连接2表+外连接1表

时间:2014-03-12 06:56:38

标签: c# linq join

我有2个内连接(3个表),但我不知道,我发现很难在LINQ中实现关于外连接的研究。如何将最后一个内部联接更改为外部联接,以便即使列(Role)为null,该列仍将连接?

这是我想要转换为LINQ的现有SQL版本:

SELECT dbo.EmployeeAccess.id, dbo.EmployeeAccess.EmpNo, dbo.EmployeeAccess.RoleID, dbo.EmployeeAccess.Active, dbo.EmployeeAccessLevel.Role, 
                  dbo.View_HCM.LNameByFName

FROM  dbo.EmployeeAccess LEFT OUTER JOIN
      dbo.EmployeeAccessLevel ON dbo.EmployeeAccess.RoleID = dbo.EmployeeAccessLevel.id INNER JOIN
      dbo.View_HCM ON dbo.EmployeeAccess.EmpNo = dbo.View_HCM.EmpNo

LINQ我现在有2个内部联接:

    (from ea in context.EmployeeAccesses
                    join vh in context.View_HCM on (Int16)ea.EmpNo equals vh.EmpNo
                    join rl in context.EmployeeAccessLevels on ea.RoleID equals rl.id 
                    select new EmployeeWithEmail{

                        EmpNum = ea.EmpNo ?? 0,
                        EmailAddress = vh.EmailAddress,                          
                        LNameByFname = vh.LNameByFName,                                  
                        Active2 = ea.Active ?? false

                    }).ToList();
        }

1 个答案:

答案 0 :(得分:1)

Linq的外连接语法使用2部分。首先是into然后是DefaultIfEmpty

在您的情况下,外部联接可能如下所示:

(from ea in context.EmployeeAccesses
join vh in context.View_HCM on (Int16)ea.EmpNo equals vh.EmpNo
join rl in context.EmployeeAccessLevels on ea.RoleID equals rl.id into outer_join
from subjoin in outer_join.DefaultIfEmpty()
select new EmployeeWithEmail{

    EmpNum = ea.EmpNo ?? 0,
    EmailAddress = vh.EmailAddress,                          
    LNameByFname = vh.LNameByFName,                                  
    Active2 = ea.Active ?? false

}).ToList();

如何在LINQ中创建外部联接有many tutorials