2013-04-08 8 views
9

ho bisogno di scrivere uno stato Linq entità che può ottenere la query SQL di seguitoLINQ to entità Join tavolo con più OR condizioni

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) 

mi sono bloccato con il seguito della sintassi

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

questo mi dà l'errore sottostante

Errore 50 Il tipo di una delle espressioni nella clausola join non è corretto. Digitare l'inferenza non riuscita nella chiamata a "Partecipa".

Come è possibile eseguire un join a più condizioni per un tavolo.

risposta

21

Non è necessario utilizzare la sintassi di join. Aggiungendo i predicati in una clausola where ha lo stesso effetto e si possono aggiungere ulteriori condizioni:

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

Bene, questo ha funzionato. Stavo cercando SO e ho trovato qualcosa di simile a dove RR.OrderedProductId/RR.SoldProductId è uguale a M.ProductID ma non ha funzionato per il mio codice. – HaBo

7

cambiare la vostra sintassi di query da utilizzare join all'utilizzo di un from clausola aggiuntiva

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

Le tue due risposte hanno funzionato per me. Spiacente, posso selezionare solo una risposta. Quindi ti sto dando il voto e selezionando @gert Arnold come risposta – HaBo

2

più join:

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