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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With