Currently, I have the following EntityFramework query to populate a report:
var reporte = ObtieneMarcaciones().GroupBy(m => m.CenterName).Select(m => new
{
Center = string.IsNullOrEmpty(m.Key) ? "(sin centro de costo)" : m.Key,
Services = m.Count()
});
ObtieneMarcaciones()
method returns the result of a SQL Server query, this way:
marcaciones.Select(m => new DatoMarcacion()
{
CenterId = m.CentroCostoId,
CenterName = m.CentroCostoNombre,
ServiceId = m.ServicioId,
ServiceName = m.Servicio.ServicioNombre
});
Where marcaciones
is just a SQL Server table (an EF6 entity).
The result of ObtieneMarcaciones(...)
is, for example,
CenterId CenterName ServiceId ServiceName
1 Name1 2 Service2
1 Name1 2 Service2
1 Name1 2 Service2
1 Name1 3 Service3
1 Name1 3 Service3
As you can see in my first code, I am grouping by CenterName
and counting ServiceId
so, the final report is:
Center Services
Name1 5
Of course I am showing only one Center
. In the real scenario, there are a lot of them.
Well, so far, so good. Now I need to separate service counts in different columns, to have a final report something like this:
Centers Service2 Service3 Total
Name1 3 2 5
It is something like generating the Service
columns dynamically. Of course, in real scenario, I don't know how many services exist.
How can I do it so that the query is ran and returned in the SQL Server engine? It should be done without calling ToList
first.