LINQ to SQL: Multiple joins ON multiple Columns. Is this possible?
LINQ to SQL: Multiple joins ON multiple Columns. Is this possible?
问题
Given:
A table named TABLE_1
with the following columns:
ID
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.
Problem:
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 :(
How do I write my query in LINQ? What am I doing wrong?
回答1
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.
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 }
...
回答2
U can also use :
var query =
from t1 in myTABLE1List
join t2 in myTABLE1List
on new { ColA=t1.ColumnA, ColB=t1.ColumnB } equals new { ColA=t2.ColumnA, ColB=t2.ColumnB }
join t3 in myTABLE1List
on new {ColC=t2.ColumnA, ColD=t2.ColumnB } equals new { ColC=t3.ColumnA, ColD=t3.ColumnB }
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2021-08-30 Escape Character in SQL Server
2021-08-30 Is it a good approach to call return inside using {} statement?
2021-08-30 What does CultureInfo.InvariantCulture mean?
2019-08-30 What do you do as a DevOps?
2019-08-30 HearthBuddy Ai调试实战1-->出牌的时候,少召唤了图腾就结束回合
2016-08-30 System.MissingMethodException: 找不到方法:
2016-08-30 Printing Array elements with Comma delimiters