I need to make a return of my database in a specific way, however I have a problem, the situation is as follows:
I have this query already tested directly on SQL Server , and it is working perfectly:
SELECT
COUNT (ate.id) AS data,
pes.tp_raca AS categories,
pes.genero AS name
FROM
Atendimento ate
INNER JOIN Pessoa pes ON pes.id = ate.pessoa_id
WHERE
ate.dt_atendimento >= '2018-08-20'
AND ate.dt_atendimento <= '2018-11-10'
GROUP BY
pes.tp_raca,
pes.genero
And returns the following result:
data categories name
1 5 Feminino
1 2 Masculino
2 5 Masculino
In the C # tag, the query looks like this:
using (var context = new SiviasContext())
{
DateTime inicio = new DateTime(2018,08,20);
DateTime fim = new DateTime(2018,11,10);
var result = context.Database.SqlQuery<List<Tuple<int, string, string>>>("SELECT COUNT (ate.id) AS data, pes.tp_raca AS categories, " +
"pes.genero AS name FROM Atendimento ate INNER JOIN Pessoa pes ON pes.id = ate.pessoa_id " +
"WHERE ate.dt_atendimento >= "+inicio.ToString("yyyy-MM-dd")+" AND ate.dt_atendimento <= "+ fim.ToString("yyyy-MM-dd") +
" GROUP BY pes.tp_raca, pes.genero").ToList();
ViewBag.result = JsonConvert.SerializeObject(result);
}
As it stands, it does not display an error, but it returns an empty list. Notice that direct execution in SQL uses the date as a string, but if I use it as a string in the C # code, it presents an error saying that it is not possible to use a string in a DateTime type. That is, it recognizes that the date attribute in the database is of type Datetime.
I tried to use the date without passing the .ToString ("yyyy-MM-dd") to format, however it also presents a complaining error of 00 (zeros) of the team contained in the date.
So, I wish you could help me with this, how do I resolve it?
===================================================== ===============
The resolution was given following the idea of @Pedro Paulo, thus:
List<RetornoConsulta> result = context.Atendimentos.Where(x => x.dt_atendimento >= dt_inicio)
.Where(x => x.dt_atendimento <= dt_fim)
.Select(g => new {
categories = g.Pessoa.tp_raca.ToString(),
name = g.Pessoa.genero
})
.GroupBy(g => new {
categories = g.categories,
name = g.name
})
.Select(g => new RetornoConsulta
{
data = g.Count(),
categories = g.Key.categories.ToString(),
name = g.Key.name
}).ToList();