[英]linq join 3 tables with or condition
我需要在LINQ中創建一個帶有3個表和OR條件的語句。
我的函數接收一個整數,我們稱之為intZ
。 我有3個表: tableA
, tableB
和tableC
。
tableA
具有列int1
, int2
和intB
。 intB
與tableB
相關。
問題: tableA
int1
或int2
可以是intZ
,它必須與一個tableC
記錄匹配。
我需要OR條件,但我不知道在哪里放置它。 它是否在where子句中? 還是在equals子句中?
目前,我知道如何加入3張桌子,但條件是殺了我。
在linq中創建語句的兩種方法有什么區別? 是否有性能影響?
編輯:好的,現在我覺得它更清楚了。 intZ
必須與intC
的tableC
相關,並且此數字可以是tableA
int1
或int2
。
只需將其添加到Where
。 在Linq2Sql中,這將被轉換為tableB上的內連接(帶或)
from a in tableA
from b in tableB.Where(x => x.A == a.A || x.B == a.B)
select new { a, b };
你不能在LINQ中的連接中使用“或”條件,因為它只支持equijoins。 但是你應該能夠在一個沒有問題的where
子句中完成它。 例如:
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 };
這可能會有所幫助。
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
};
對於我的生活,我無法得到。在我的查詢中可以工作(也許這就是我如何使用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.