gpt4 book ai didi

c# - linq 中等效的 SQL 限制

转载 作者:行者123 更新时间:2023-11-28 23:55:38 25 4
gpt4 key购买 nike

我正在寻找与下面的 SQL 查询等效的 linq。

select * from tableA as A
left join tableB as B on A.Id = B.Id
left join tableC as C on B.Id = C.Id
left join tableD as D on C.Id = D.Id and D.OrderId = B.OrderId

我最感兴趣的是如何使用这个表达式正确地限制结果:

 and D.OrderId = B.OrderId

C#代码

var data = from a in tableA

join innerB in tableB on a.Id equals innerB.Id into INNERB
from b in INNERB.DefaultIfEmpty()

join innerC in tableC on b.Id equals innerC.Id into INNERC
from c in INNERC.DefaultIfEmpty()

join innerD in tableD on c.Id equals innerD.Id into INNERD
from d in INNERD.DefaultIfEmpty().Where(p=>p.OrderId == b.OrderId)

linq 从数据库返回的结果与 SQL 查询不匹配。如果您能向我解释如何使用应用于每一行的先前连接表中的变量,我们将不胜感激。

我也试过了,但是编译器抛出一个错误,“b 的名称在当前上下文中不存在”:

join innerD in tableD.Where(p=>p.OrderId == b.OrderId) on c.Id equals innerD.Id into INNERD
from d in INNERD.DefaultIfEmpty()

最佳答案

请参阅此答案以获得更简单的 LEFT JOIN 语法:https://stackoverflow.com/a/4739738/1869660

您的查询将是:

var data = from a in tableA
from b in tableB.Where(x => x.Id == a.Id)
.DefaultIfEmpty()
from c in tableC.Where(x => x.Id == b.Id)
.DefaultIfEmpty()
from d in tableC.Where(x => (x.Id == c.Id) && (x.OrderId == b.OrderId))
.DefaultIfEmpty()
select ...

关于c# - linq 中等效的 SQL 限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31772337/

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