问题描述
我在使用一个相当简单的 sql select 语句的 join/where 子句中苦苦挣扎.
I'm struggling with a join/where clause with what is a rather simple sql select statement.
我正在尝试从 tb1 中检索产品信息列表,其中 where 条件位于 tbl2 中,但这必须由三个不同的列连接.
I am trying to retrieve a list of product information from tb1 with the where condition behind situated in tbl2 but this must be joined by three different columns.
所以 SQL 看起来像这样:
so the SQL would look something along the lines of:
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 子句,字符串作为参数传入;所有其他列都在上下文中.
ColX is the main where clause with the string to be passed in as parameter; all other columns are within the contexts.
如何使用 where 子句实现多个连接?
How do you implement multiple joins with a where clause?
并且朝着正确的方向推进,非常感谢.
And shoves in the right direction, muchly appreciated.
推荐答案
要在 LINQ 中连接多个字段,您必须创建一个包含要比较的列的新匿名类型,然后在连接中使用该匿名类型:
To join on multiple field in LINQ, you have to create a new anonymous type containing the columns you want to compare and then use that anonymous type in the join:
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 语法:
And here is the equivalent Lambda Syntax:
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);
如您所见,在连接的情况下,查询语法通常会生成更易于阅读的语句.
As you can see, in the case of joins, query syntax usually produces an easier to read statement.
这篇关于LINQ 加入 Where 子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!