2012-10-04 14 views
6

Sto convertendo una query SQL in LINQ che crea un join sinistro con mapping 1-a-1 e deve essere in Method Syntax. Mi sono tolto i capelli cercando di realizzare questo senza velare. Posso farlo in Lambda Sintassi. Di seguito è la query di esempio che sto cercando di eseguire. Non sono codice reale. Qualcuno potrebbe far notare cosa sto facendo male?JOIN e LEFT JOIN equivalenti in LINQ con Method Sintassi

SQL:

SELECT item.*, item_status.* 
FROM item 
LEFT JOIN item_status 
    ON item.ID = item_status.itemID 
    AND item_status.FLAGGED = true 
WHERE item.published_date > "2008-06-19" 

LINQ:

var linq_query = (
    from selected_item in item 
    join selected_item_status in item_status 
     on selected_item.ID equals item_status.itemID into joined 
    from item_status in joined.DefaultIfEmpty() 
    where item_status.FLAGGED = true 
    select new {selected_item, selected_item_status}).ToList(); 
+0

Come ti diciamo cosa c'è che non va nel tuo codice se non è in realtà codice? Possiamo anche vedere la classe 'Item',' item_status', e la classe in cui inserisci l'elenco di tipo anonimo, per favore? –

risposta

8

Il join ... into diventa un GroupJoin e la seconda from diventa un SelectMany:

var linq_query = Item 
    .GroupJoin(
     item_status.Where(x => x.selected_item_status.FLAGGED), // EDIT: Where clause moved here. 
     selected_item => selected_item.ID, 
     selected_item_status => selected_item_status.itemID, 
     (selected_item, joined) => new 
     { 
      selected_item, 
      statuses = joined.DefaultWithEmpty(), 
     }) 
    .SelectMany(x => x.statuses.Select(selected_item_status => new 
    { 
     x.selected_item, 
     selected_item_status, 
    })) 
    // EDIT: Removed where clause. 
    .ToList(); 

Sembra che il Where fa la sinistra l'unione esterna non è necessaria, come n gli stati ull verranno comunque filtrati.

MODIFICA: No, dopo aver esaminato l'SQL sembra che la query LINQ sia leggermente errata. Dovrebbe essere:

var linq_query = (
    from selected_item in item 
    join selected_item_status 
     in (
      from status in item_status 
      where status.FLAGGED 
      select status) 
     on selected_item.ID equals item_status.itemID into joined 
    from item_status in joined.DefaultIfEmpty() 
    select new {selected_item, selected_item_status}).ToList(); 
+0

Grazie! Non mi è mai venuto in mente di avere la clausola where sul tavolo unito lì. – s1300045

+0

Grazie per questo - ho appena ricevuto questa risposta ed è quello che sto cercando. Come ci penso, ponendo la clausola where in quel punto più simile a SQl rispetto alla sintassi non Method linq. – EGP