Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linq join 3 tables with or condition

Tags:

c#

.net

sql

join

linq

I need to create a statement in LINQ with 3 tables and OR condition.

My function receives an integer, lets call it intZ. I have 3 tables: tableA, tableB and tableC.

tableA has columns int1, int2 and intB. intB is related to tableB.

problem: int1 or int2 of tableA can be intZ and it has to match with one tableC record.

I need an OR condition, but I have no idea where to place it. Does it go in the where clause? Or in the equals clause?

At the moment, I know how to join 3 tables, but the condition is killing me.

What is the difference between the two ways to create statements in linq? Is there a performance impact?

edit: Okay, now I think it's more clear. intZ has to be related with intC from tableC, and this number can be int1 or int2 of tableA.

enter image description here

like image 215
Guillermo Varini Avatar asked Dec 03 '22 05:12

Guillermo Varini


2 Answers

Just add it to a Where. In Linq2Sql this will be translated to an inner join (with or) on tableB

from a in tableA
from b in tableB.Where(x => x.A == a.A || x.B == a.B)
select new { a, b };
like image 197
Magnus Avatar answered Dec 22 '22 00:12

Magnus


You can't use an "or" condition in joins in LINQ, as it only supports equijoins. But you should be able to do it in a where clause with no problems. For example:

var query = from rowC in tableC
            where rowC.intC == intZ
            from rowA in tableA
            where rowA.int1 == rowC.intC || rowA.int2 == rowC.intC
            join rowB in tableB on rowA.intB equals rowB.intB
            select new { rowA, rowB, rowC };
like image 39
Jon Skeet Avatar answered Dec 22 '22 00:12

Jon Skeet