2013-04-08 46 views
9

我需要写一个LINQ实体状态,可以得到下面的SQL查询LINQ到实体加入表拥有多个或条件

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

我该如何做一个表的多条件连接。

回答

21

您不必使用连接语法。在where条款添加谓词具有相同的效果,你可以添加更多的条件:使用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(); 
+0

那么这工作。我一直在寻找,并发现像RR.OrderedProductId/RR.SoldProductId等于M.ProductID的地方,但这对我的代码无效。 – HaBo 2013-04-08 19:47:07

7

更改您的查询语法:

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

你的两个答案都适合我。对不起,我只能选择一个答案。所以我给你投票并选择@gert Arnold作为答案 – HaBo 2013-04-08 19:48:42

2

多加入

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