Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do Join in Linq query on column A or column B

Tags:

c#

.net

sql

linq

I want to perform a join on a any of the two columns that has the given value

How to convert for example the following SQL query to it's equivalent in Linq (method syntax):

select f.Id fId, b.Id bId from Foo f
inner join Bar b on f.FooVal = b.BarValCol1 or f.FooVal = b.BarValCol2

I started doing the following :

Context.Foos
.Join(Context.Bars, f => f.FooVal, b => b.BarValCol1 [OR?] b.BarValCol2, (f, b) => new { f, b })
.Select(bf => new { fId = bf.f.Id, bId = bf.b.Id })

(in this example the two columns contain integer values)

like image 994
Uentee Avatar asked Jan 27 '23 16:01

Uentee


1 Answers

INNER JOIN is a more readable syntax, but it can be translated, in pure SQL, into cartesian product of the tables filtered with a WHERE clause.

So we can simply use a WHERE clause and build the linq from that:

from x in Foo
from y in Bar
    .Where(y => y.field1 == x.field1 || y.field2 == x.field2)

Ps: INNER JOIN and WHERE are not evaluated at the same time in SQL so they are not equivalent. ON condition filter the INNER JOIN then the WHERE is apply. But even they will have the same result but not the same execution plan depending on the Database of course.

like image 89
Drag and Drop Avatar answered Jan 30 '23 04:01

Drag and Drop