gpt4 book ai didi

LINQ 加入 Where 子句

转载 作者:行者123 更新时间:2023-12-03 11:31:50 33 4
gpt4 key购买 nike

我正在努力使用一个相当简单的 sql select 语句的 join/where 子句。

我正在尝试从 tb1 中检索产品信息列表,其中 where 条件位于 tbl2 中,但这必须由三个不同的列连接。

所以 SQL 看起来类似于:

SELECT     tb1.*
FROM tb2 INNER JOIN
tb1 ON tb2.Col1 = tb1. Col1 AND tb2.Col2 = tb1. Col2 AND
tb2.Col3 = tb1.Col3
WHERE (tb2.Col1 = col1) AND (tb2.Col2 = col2) AND (tb2.Col4 = string)

ColX 是主要的 where 子句,字符串作为参数传入;所有其他列都在上下文中。

如何使用 where 子句实现多个连接?

并朝着正确的方向推进,非常感谢。

最佳答案

要在 LINQ 中连接多个字段,您必须创建一个包含要比较的列的新匿名类型,然后在连接中使用该匿名类型:

var results = from t1 in context.tb1
join t2 in context.tb2
on new { t1.Col1, t1.Col2, t1.Col3 } equals
new { t2.Col1, t2.Col2, t2.Col3 }
where t2.Col1 == col1 && t2.Col2 == col2 && t2.Col4 == someString
select t1;

这是等效的 Lambda 语法:
var results = context.tb1.Join(
context.tb2,
t1 => new { t1.Col1, t1.Col2, t1.Col3 },
t2 => new { t2.Col1, t2.Col2, t2.Col3 },
(t1, t2) => new { t1, t2 })
.Where(o => o.t2.Col1 == col1
&& o.t2.Col2 == col2
&& o.t2.Col4 == someString)
.Select(o => o.t1);

如您所见,在连接的情况下,查询语法通常会生成更易于阅读的语句。

关于LINQ 加入 Where 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3547652/

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