簡體   English   中英

具有多個OR條件的Linq to Entity Join表

[英]Linq to Entity Join table with multiple OR conditions

我需要編寫一個可以獲得以下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 join子句中某個表達式的類型不正確。 調用“加入”時類型推斷失敗。

如何為表執行多條件連接。

您不必使用連接語法。 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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM