C# 具有多个OR条件的Linq到实体联接表
我需要编写一个Linq实体状态,它可以获得下面的SQL查询C# 具有多个OR条件的Linq到实体联接表,c#,linq,entity-framework,linq-to-entities,C#,Linq,Entity Framework,Linq To Entities,我需要编写一个Linq实体状态,它可以获得下面的SQL查询 SELECT RR.OrderId FROM dbo.TableOne RR JOIN dbo.TableTwo M ON RR.OrderedProductId = M.ProductID OR RR.SoldProductId= M.ProductID WHERE RR.StatusID IN ( 1, 4, 5, 6, 7 ) 我被下面的语法难住了 int[] statusIds = new in
SELECT RR.OrderId
FROM dbo.TableOne RR
JOIN dbo.TableTwo M ON RR.OrderedProductId = M.ProductID OR RR.SoldProductId= M.ProductID
WHERE RR.StatusID IN ( 1, 4, 5, 6, 7 )
我被下面的语法难住了
int[] statusIds = new int[] { 1, 4, 5, 6, 7 };
using (Entities context = new Entities())
{
var query = (from RR in context.TableOne
join M in context.TableTwo on new { RR.OrderedProductId, RR.SoldProductId} equals new { M.ProductID }
where RR.CustomerID == CustomerID
&& statusIds.Any(x => x.Equals(RR.StatusID.Value))
select RR.OrderId).ToArray();
}
这给了我以下的错误
错误50 join子句中某个表达式的类型不正确。调用“Join”时类型推断失败。
如何对表执行多条件联接。不必使用联接语法。在
where
子句中添加谓词具有相同的效果,您可以添加更多条件:
var query = (from RR in context.TableOne
from M in context.TableTwo
where RR.OrderedProductId == M.ProductID
|| RR.SoldProductId == M.ProductID // Your join
where RR.CustomerID == CustomerID
&& statusIds.Any(x => x.Equals(RR.StatusID.Value))
select RR.OrderId).ToArray();
将查询语法从使用
join
更改为使用附加的from
子句
var query = (from RR in context.TableOne
from M in context.TableTwo.Where(x => x.ProductID == RR.OrderedProductId || x.ProductID == RR.SoldProductId)
where statusIds.Any(x => x.Equals(RR.StatusID.Value))
select RR.OrderId).ToArray();
多重联接:
var query = (from RR in context.TableOne
join M in context.TableTwo on new { oId = RR.OrderedProductId, sId = RR.SoldProductId} equals new { oId = M.ProductID, sId = M.ProductID }
where RR.CustomerID == CustomerID
&& statusIds.Any(x => x.Equals(RR.StatusID.Value))
select RR.OrderId).ToArray();
好吧,这起作用了。我查看了一下,发现了类似的地方,其中RR.OrderedProductId/RR.SoldProductId等于M.ProductID,但这对我的代码不起作用。您的两个答案对我都起作用。对不起,我只能选择一个答案。所以我给你们投票,选择@gert Arnold作为答案将在……上创建一个
。。。而且……
不是。。。或者…query