linq中的SQL限制等效

时间:2015-08-02 13:24:35

标签: c# mysql sql linq

我正在寻找一个等同于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从db返回的结果与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()

1 个答案:

答案 0 :(得分:1)

有关更简单的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 ...