我想将此SQL查询转换为linq:
select * from A a
join B b on ( (a.level1= b.PerimeterID and b.PerimeterLevelID = 1)
OR (a.level2= b.PerimeterID and b.PerimeterLevelID = 2)
OR (a.level3= b.PerimeterID and b.PerimeterLevelID = 3)
)
我尝试过的事情:
from a in A
join b in B on new {PerimeterID = a.level1, PerimeterLevelID = 1 } equals new { b.PerimeterID, b.PerimeterLevelID }
where (a.level2 == b.PerimeterID && b.PerimeterLevelID == 2) ||
(a.level3 == b.PerimeterID && b.PerimeterLevelID == 3)
它生成此sql查询:
select * from A a
join B b on (a.level1= b.PerimeterID and b.PerimeterLevelID = 1)
where (a.level2= b.PerimeterID and b.PerimeterLevelID = 2)
OR (a.level3= b.PerimeterID and b.PerimeterLevelID = 3))
我也尝试过Linqer,但是它不能将OR转换为linq
SQL无法转换为LINQ:或
我要怎么做才能转换此SQL查询
答案 0 :(得分:1)
内部联接等效于过滤的交叉联接。
from a in A
from b in B
where (a.level1 == b.PerimeterID && b.PerimeterLevelID == 1) ||
(a.level2 == b.PerimeterID && b.PerimeterLevelID == 2) ||
(a.level3 == b.PerimeterID && b.PerimeterLevelID == 3)
select new {a,b};
?
答案 1 :(得分:0)
您可以尝试使用DefaultIfEmpty()
。联接的行为类似于使用此命令的左联接
from a in A
from b in B.DefaultIfempty()
where ( (a.level1== b.PerimeterID && b.PerimeterLevelID == 1)
|| (a.level2== b.PerimeterID && b.PerimeterLevelID == 2)
|| (a.level3== b.PerimeterID && b.PerimeterLevelID == 3))
答案 2 :(得分:0)
我认为该查询会有所帮助
var query = from a in context.A
join b1 in context.B
on new { Perimeter = a.level1, LevelID = 1 }
equals new { Perimeter = b1.PerimeterID, LevelID = b1.PerimeterLevelID }
join b2 in context.B
on new { Perimeter = a.level2, LevelID = 2 }
equals new { Perimeter = b2.PerimeterID, LevelID = b2.PerimeterLevelID }
join b3 in context.B
on new { Perimeter = a.level3, LevelID = 3 }
equals new { Perimeter = b3.PerimeterID, LevelID = b3.PerimeterLevelID }
select new
{
a,
b1,
b2,
b3
};