Raggruppamento e conteggio con Linq To SQL
-
20-08-2019 - |
Domanda
Ho una tabella di artisti e una tabella di stile.
tabella degli artisti: id nome styleid
tabella di stile id nome
Un artista ha un ID di stile
Sto cercando di restituire un riepilogo dello stile che include ID stile, nome stile e numero di artisti appartenenti a quello stile.
Ho la seguente dichiarazione che mi dà l'id e il numero di artisti, ma non riesco a vedere come ottenere anche il nome dello stile.
return from s in DBContext.Styles
join artist in DBContext.Artists on s.ID equals artist.StyleID
group artist by artist.StyleID into a
select new DTO.StyleSummary
{
ID = a.Key,
NumberOfArtists = a.Count()
};
È possibile con un solo viaggio di andata e ritorno?
Soluzione
Puoi utilizzare un tipo anonimo per raggruppare in base a più valori:
return from s in DBContext.Styles
join artist in DBContext.Artists on s.ID equals artist.StyleID
group artist by new {s.ID, s.Name } into a
select new DTO.StyleSummary {
ID = a.Key.ID,
Name = a.Key.Name,
NumberOfArtists = a.Count()
};
Altri suggerimenti
Puoi fare un conteggio in una sottoquery come questa ...
var results =
from s in DBContext.Styles
select new
{
Id = s.Key,
NumberOfArtists =
(
from a in DBContext.Artists
where a.StyleId = s.StyleId
select a
).Count()
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow