使用Linq to Entity连接带有多个OR条件的表格

13

我需要编写一个Linq-Entity状态,以获取以下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 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”时,类型推断失败。

如何对表进行多条件连接?

3个回答

27

您不一定需要使用连接语法。将谓词添加到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();

这个方法可行。我在 Stack Overflow 上找到了类似 RR.OrderedProductId / RR.SoldProductId 等于 M.ProductID 的代码,但是对我的代码不起作用。 - HaBo

7
将查询语法从使用 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();

你们两个的答案都对我有帮助。非常抱歉,我只能选择一个答案。所以我会给你点赞并选择@gert Arnold的答案。 - HaBo

3

多表连接:

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();

将创建一个“on ... and ...”而不是“on ... or ...”查询。 - Steffen Mangold

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接