gpt4 book ai didi

c# - 多个左外连接与 lambda 表达式

转载 作者:太空狗 更新时间:2023-10-29 23:31:32 26 4
gpt4 key购买 nike

我有一个 SQL 查询来处理像这样的 Lambda 表达式,通常有比这个例子更多的连接。

select Table2.a,
Table2.b,
Table2.c,
Table2.d
from Table1
LEFT OUTER JOIN Table2
ON Table2.a = Table1.a and
Table2.b = Table1.b and
Table2.c = Table1.c
LEFT OUTER JOIN Table3
ON Table3.b = Table1.b AND
Table3.c = Table1.c AND
Table3.d = Table1.d
where ( Table1.a = ValueA )
order by Table3.f

我正在使用 Join() Lambda 表达式执行此操作,但我在 SQL Server 分析器中看到这会生成一个 INNER JOIN,我需要一个 LEFT OUTER JOIN。

这就是我用 Join() 做的

var RS = DBContext.Table1.Join(DBContext.Table2,
Table1 => new {Table1.a, Table1.b, Table1.c},
Table2 => new {Table1.a, Table1.b, Table1.c},
(Table1, Table2) => new {Table1})
.Join(DBContext.Table3,
LastJoin => new {LastJoin.Table1.b, LastJoin.Table1.c, LastJoin.Table1.d},
Table3 => new {Table3.b, Table3.c, Table3.d},
(LastJoin,Table3) => new {LastJoin.Table1, Table3})
.Where (LastTable => LastTable.Table1.a == ValueA)
.OrderBy(LastTable => LastTable.Table3.f)
.Select (LastTable => new {LastTable.Table1, LastTable.Table3});

我一直在读到它可以通过 DefaultIfEmpty() 或 GroupJoin() 来完成,但我还没有找到任何包含多个 LEFT OUTER JOIN 的复杂示例。

最佳答案

为什么不尝试使用 linq 查询,与 lambda 表达式相比,它也更容易编写和理解。我有这样的实现:

var products = 
from p in this.Products
from cat in this.ProductCategoryProducts
.Where(c => c.ProductID == p.ProductID).DefaultIfEmpty()

from pc in this.ProductCategories
.Where(pc => ac.ProductCategoryID == cat.ProductCategoryID).DefaultIfEmpty()

where p.ProductID == productID
select new
{
ProductID = p.ProductID,
Heading = p.Heading,
Category = pc.ProductCategory
};
return products ;

关于c# - 多个左外连接与 lambda 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20729315/

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