[英]linq join 3 tables with or condition
I need to create a statement in LINQ with 3 tables and OR condition. 我需要在LINQ中创建一个带有3个表和OR条件的语句。
My function receives an integer, lets call it intZ
. 我的函数接收一个整数,我们称之为intZ
。 I have 3 tables: tableA
, tableB
and tableC
. 我有3个表: tableA
, tableB
和tableC
。
tableA
has columns int1
, int2
and intB
. tableA
具有列int1
, int2
和intB
。 intB
is related to tableB
. intB
与tableB
相关。
problem: int1
or int2
of tableA
can be intZ
and it has to match with one tableC
record. 问题: tableA
int1
或int2
可以是intZ
,它必须与一个tableC
记录匹配。
I need an OR condition, but I have no idea where to place it. 我需要OR条件,但我不知道在哪里放置它。 Does it go in the where clause? 它是否在where子句中? Or in the equals clause? 还是在equals子句中?
At the moment, I know how to join 3 tables, but the condition is killing me. 目前,我知道如何加入3张桌子,但条件是杀了我。
What is the difference between the two ways to create statements in linq? 在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
. intZ
必须与intC
的tableC
相关,并且此数字可以是tableA
int1
或int2
。
Just add it to a Where
. 只需将其添加到Where
。 In Linq2Sql this will be translated to an inner join (with or) on tableB 在Linq2Sql中,这将被转换为tableB上的内连接(带或)
from a in tableA
from b in tableB.Where(x => x.A == a.A || x.B == a.B)
select new { a, b };
You can't use an "or" condition in joins in LINQ, as it only supports equijoins. 你不能在LINQ中的连接中使用“或”条件,因为它只支持equijoins。 But you should be able to do it in a where
clause with no problems. 但是你应该能够在一个没有问题的where
子句中完成它。 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 };
This may be helpful. 这可能会有所帮助。
var locations = from r1 in
(from a in context.A
join b in context.B
on a.ID equals b.ID
select new
{
a.Prop1,
a.Prop2,
b.Prop3,
b.ID
})
join c in context.C
on r1.ID equals c.ID
select new
{
r1.Prop1,
r2.Prop2,
r2.Prop3,
c.Prop4
};
For the life of me, I couldn't get the .Where to work in my query (perhaps it's how I'm using LinqPad) but I was able to get the following to work: 对于我的生活,我无法得到。在我的查询中可以工作(也许这就是我如何使用LinqPad)但我能够得到以下工作:
from s in Stores
join a in Areas on s.AreaID equals a.ROWID
join r in Regions on a.RegionID equals r.ROWID
join e in Employees on 1 equals 1 // <-- produces a cartesian product
join t in Titles on e.TitleID equals t.ROWID
where e.AreaID == a.ROWID || e.RegionID == r.ROWID // <--filters the data based on OR stmt
where s.StoreNum == 469
select new { r.RegionName, a.AreaName, s.StoreNum, s.StoreName, t.JobCode, e.FirstName, e.LastName }
尝试这个:-
var result= tableA.SelectMany(a => tableB.Where(x => x.A == a.A || x.B == a.B), (a, b) => new {a, b});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.