具有多个OR条件的链接到实体连接表

本文关键字:链接 实体 连接 条件 OR | 更新日期: 2023-09-27 18:08:01

我需要写一个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"时类型推断失败。

具有多个OR条件的链接到实体连接表

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