【问题标题】:Linq to Entity Join table with multiple OR conditions具有多个 OR 条件的 Linq to Entity Join 表
【发布时间】:2013-04-11 12:40:20
【问题描述】:

我需要写一个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 连接子句中的其中一个表达式的类型不正确。调用“加入”时类型推断失败。

如何对表进行多条件联接。

【问题讨论】:

    标签: c# linq entity-framework linq-to-entities


    【解决方案1】:

    您不必使用连接语法。在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();
    

    【讨论】:

    • 这行得通。我正在查看 SO,发现类似于 RR.OrderedProductId / RR.SoldProductId 等于 M.ProductID 的地方,但这不适用于我的代码。
    【解决方案2】:

    将查询语法从使用 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 作为答案
    【解决方案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 ... 查询
    猜你喜欢
    • 2023-03-31
    • 2017-04-07
    • 1970-01-01
    • 2021-08-12
    • 2011-12-07
    • 1970-01-01
    • 2017-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多