2011-02-10 28 views
5

Ciao potrei sapere come fare una condizione di "caso" in uso con linq? Il codice commentato è la mia domanda. come faccio a mettere la condizione lì? il mio codice:linq join con condizione condizione

var r = from u in Users 
    join p in Payments on u.Id equals p.UserId 
    join soi in SaleOrderItems on p.ReferenceId equals soi.Id 
      //if soi.InventoryTypeId == 1 
       //then join i in Inventories on soi.InventoryOrCourseId equals i.Id 
      //elseif soi.InventorytypeId ==2 
       //then join c in Courses on soi.InventoryOrCourseId equals c.Id 
    where u.Id == 5 
    select new{ u, p, soi, either i or c}; 

risposta

2

Devi usare un po 'di outer join trucco per ottenere questo risultato, un metodo semplice è via DefaultIfEmpty(). In sostanza si crea un INNER JOIN poi espandere con righe mancanti:

var r = from u in Users 
    join p in Payments on u.Id equals p.UserId 
    join soi in SaleOrderItems on p.ReferenceId equals soi.Id 
    join i in Inventories on new {a = soi.InventoryTypeId, b = soi.InventoryOrCourseId } equals new {a = 1, b = i.Id} into g1 
    from oi in g1.DefaultIfEmpty() 
    join c in Courses on new {a = soi.InventoryTypeId, b = soi.InventoryOrCourseId } equals new {a = 2, b = c.Id} into g2 
    from oc in g2.DefaultIfEmpty() 
    where u.Id == 5 
    select new{ u, p, soi, ic = oi ?? oc}; 

stare attenti a quest'ultima affermazione ic = oi ?? oc, dal momento che i tipi si differenziano il tipo anonimo utilizzerà dichiarazione System.Object in modo che possa ospitare entrambi i tipi, se si vuoi usare un forte supporto tipizzato forse una soluzione migliore sarebbe quella di restituire sia oc che ic e quindi testare. È meglio decidere in base a come usi questa query in ritardo.

+0

@mmix ciao ho ricevuto questo errore "Il tipo di una delle espressioni nella clausola join non è corretto. Tipo di inferenza non riuscita nella chiamata a 'GroupJoin'." alla riga unire i in Inventories su new {a ... – VeecoTech

+0

Che tipo è 'soi.InventoryTypeId'? Dal momento che immagino 'type (soi.InventoryOrCourseId)' equals 'type (Inventory.Id)' allora deve essere che 'soi.InventoryTypeId' non è' int'. Se è così, decorare le costanti 1 e 2 con un suffisso di tipo corretto (U, L, ecc.) – mmix

+0

@mmix: sì entrambi sono esattamente int – VeecoTech