2013-04-08 43 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();