如何在 2 个谓词上对 2 个表进行 LINQ 左连接?
Posted
技术标签:
【中文标题】如何在 2 个谓词上对 2 个表进行 LINQ 左连接?【英文标题】:How to do LINQ left joins on 2 predicates to 2 tables? 【发布时间】:2021-05-15 10:22:25 【问题描述】:SELECT *
FROM A
LEFT JOIN B ON A.HelloID = B.HelloID
LEFT JOIN C ON A.BusyID = C.BusyID AND B.MemID = C.MemID
我尝试了以下方法:
var list = from A in this.A
join B in this.B
on A.HelloID equals B.HelloID into bgj
from subb in bgj.DefaultIfEmpty()
join C in this.C
on B.MemID equals C.MemID into cgj
from subc in cgj.DefaultIfEmpty()
on A.BusyID equals C.BusyID into cgj2
from subc2 in cgj2.DefaultIfEmpty()
但这不起作用,有什么想法吗?
【问题讨论】:
一方面,应该是.DefaultIfEmpty()
而不是.DefaultIfempty
好电话!让我补充一下。
【参考方案1】:
试试这个:
var list = from A in this.A
join B in this.B
on A.HelloID equals B.HelloID into bgj
from B in bgj.DefaultIfEmpty()
join C in this.C
on A.BusyId equals C.BusyId into cgj
from C in cgj.DefaultIfEmpty()
where B.MemID == C.MemID
您应该澄清有关 MemID 和 BusyId 的问题。如果它们可以为空。在这种情况下,最后一行可能是这样的:
where (B.MemID==null || B.MemID == C.MemID )
//Or
where ((B.MemID==null && C.MemID==null) || (B.MemID == C.MemID ))
【讨论】:
这种导致C.MemID是强制的,变成了inner join而不是left join?【参考方案2】:var list = from A in this.A
join B in this.B
on A.HelloID equals B.HelloID into bgj
from subb in bgj.DefaultIfEmpty()
join C in this.C
on new colA = A.BusyID, colB = B.MemID equals new colA = C.BusyID, colB = C.MemID into cgj
from subc in cgj.DefaultIfEmpty()
【讨论】:
以上是关于如何在 2 个谓词上对 2 个表进行 LINQ 左连接?的主要内容,如果未能解决你的问题,请参考以下文章