gpt4 book ai didi

c# - LINQ:内连接2表+外连接1表

转载 作者:太空宇宙 更新时间:2023-11-03 13:26:13 25 4
gpt4 key购买 nike

我有 2 个内部联接(3 个表),但我不知道,而且我发现很难在 LINQ 中实现我对外部联接的研究。如何将最后一个内部连接更改为外部连接,这样即使列(角色)为空,列仍将连接?

这是我想转换为 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

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

    (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();
}

最佳答案

Linq 的外连接语法使用两部分。首先是 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();

many tutorials关于如何在 LINQ 中创建外部联接。

关于c# - LINQ:内连接2表+外连接1表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22344108/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com