13

我需要编写一个可以获取以下 SQL 查询的 Linq-Entity 状态

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 连接子句中的表达式之一的类型不正确。对“加入”的调用中的类型推断失败。

如何为表执行多条件联接。

4

3 回答 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();
于 2013-04-08T19:37:42.310 回答
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();
于 2013-04-08T19:38:00.837 回答
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();
于 2013-04-11T04:40:20.930 回答