问题描述
考虑:
命名的表 TABLE_1
通过下列:
-
ID
-
ColumnA
-
ColumnB
-
ColumnC
ID
ColumnA
ColumnB
ColumnC
我有SQL查询,其中 TABLE_1
加入本身基于两次关闭 ColumnA
,的ColumnB
, ColumnC
。查询可能是这个样子:
I have SQL query where TABLE_1
joins on itself twice based off of ColumnA
, ColumnB
, ColumnC
. The query might look something like this:
Select t1.ID, t2.ID, t3.ID
From TABLE_1 t1
Left Join TABLE_1 t2 On
t1.ColumnA = t2.ColumnA
And t1.ColumnB = t2.ColumnB
And t1.ColumnC = t2.ColumnC
Left Join TABLE_1 t3 On
t2.ColumnA = t3.ColumnA
And t2.ColumnB = t3.ColumnB
And t2.ColumnC = t3.ColumnC
... and query continues on etc.
问题:
我需要查询的LINQ被重写。我试着采取刺伤它:
I need that Query to be rewritten in LINQ. I've tried taking a stab at it:
var query =
from t1 in myTABLE1List // List<TABLE_1>
join t2 in myTABLE1List
on t1.ColumnA equals t2.ColumnA
&& t1.ColumnB equals t2.ColumnA
// ... and at this point intellisense is making it very obvious
// I am doing something wrong :(
我怎样写我的LINQ查询?我在做什么错了?
How do I write my query in LINQ? What am I doing wrong?
推荐答案
入世对在LINQ to SQL多列是一个有点不同。
Joining on multiple columns in Linq to SQL is a little different.
var query =
from t1 in myTABLE1List // List<TABLE_1>
join t2 in myTABLE1List
on new { t1.ColumnA, t1.ColumnB } equals new { t2.ColumnA, t2.ColumnB }
...
您必须利用匿名类型并撰写类型要比较对多个列。
You have to take advantage of anonymous types and compose a type for the multiple columns you wish to compare against.
这似乎在第一混乱,但一旦你使用SQL从EX pressions构成方式熟悉它将使很多更有意义,在幕后,这将产生的加盟你正在寻找的类型。
This seems confusing at first but once you get acquainted with the way the SQL is composed from the expressions it will make a lot more sense, under the covers this will generate the type of join you are looking for.
修改添加例如,对于第二个连接基于评论。
EDIT Adding example for second join based on comment.
var query =
from t1 in myTABLE1List // List<TABLE_1>
join t2 in myTABLE1List
on new { A = t1.ColumnA, B = t1.ColumnB } equals new { A = t2.ColumnA, B = t2.ColumnB }
join t3 in myTABLE1List
on new { A = t2.ColumnA, B = t2.ColumnB } equals new { A = t3.ColumnA, B = t3.ColumnB }
...
这篇关于LINQ to SQL的:多加入多个列。这可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!