2009-07-31 6 views
3

J'essaye de convertir ce T-SQL en Linq To SQL mais je ne peux pas travailler sur le groupe par des fonctions agrégées. Toute aide bienvenue.Linq to SQL avec Group par

select c.ClientID, GivenName, Surname, max(a.Address), max(t.Value) 
from Client c 
left join ClientAddress a on c.ClientID = a.ClientID 
left join ClientContact t on c.ClientID = t.ClientID 
group by c.ClientID, GivenName, Surname 

Répondre

3

Pour groupe par une clé composite, vous utilisez généralement un type anonyme:

var qry = from x in someSource 
       group x by new { x.ClientID, x.GivenName, x.Surname } into grp 
       select new { grp.Key, Address = grp.Max(x => x.Address), 
        Value = grp.Max(x => x.Value) }; 
0

La réponse exacte, je suis venu avec était

public IQueryable<ClientSearchDTO> GetClientsDTO() 
     { 
      return (from client in this.Context.Clients 
        join address in this.Context.ClientAddresses on client.ClientID equals address.ClientID 
        join contact in this.Context.ClientContacts on client.ClientID equals contact.ClientID     
        where contact.ContactType == "Phone" 
        group client by new { client.ClientID, client.Surname, client.GivenName } into clientGroup 
        select new ClientSearchDTO() 
        { 
         ClientID = clientGroup.Key.ClientID, 
         Surname = clientGroup.Key.Surname, 
         GivenName = clientGroup.Key.GivenName, 
         Address = clientGroup.Max(x => x.ClientAddresses.FirstOrDefault().Address), 
         PhoneNumber = clientGroup.Max(x => x.ClientContacts.FirstOrDefault().Value) 
        }); 
     }