简体   繁体   中英

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

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.

You could use your LINQ twice:

Context.Foos
  .Join(Context.Bars, f => f.FooVal, b => b.BarValCol1, (f, b) => new { f, b })
  .Select(bf => new { fId = bf.f.Id, bId = bf.b.Id }).ToList().AddRange(
  Context.Foos
    .Join(Context.Bars, f => f.FooVal, b => b.BarValCol2, (f, b) => new { f, b })
    .Select(bf => new { fId = bf.f.Id, bId = bf.b.Id })
  ).Distinct();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM