3
I’m doing a query that has some joins and a Count, but I want to do it with Linq.
This is my Query.
sbSQL.Append("SELECT grproj.cdgruproj as Id, grproj.dsgruproj as DescricaoGrupoProjeto, ");
sbSQL.Append("(SELECT COUNT(*) ");
sbSQL.Append(" FROM usufrm ");
sbSQL.Append(" WHERE usufrm.cdfrm = form.cdfrm ");
sbSQL.Append(" AND usufrm.sgproj = proj.sgproj ");
sbSQL.Append(" AND usufrm.tpproj = tproj.tpproj ");
sbSQL.Append(" AND usufrm.dtcan IS NULL) as QuantidadeDeUsuarios ");
sbSQL.Append("FROM grproj ");
sbSQL.Append("INNER JOIN proj ON grproj.cdgruproj = proj.cdgruproj ");
sbSQL.Append("INNER JOIN tproj ON proj.tpproj = tproj.tpproj ");
sbSQL.Append("INNER JOIN projfr ON proj.sgproj = projfr.sgproj AND proj.tpproj = projfr.tpproj ");
sbSQL.Append("INNER JOIN form ON form.cdfrm = projfr.cdfrm ");
sbSQL.Append("WHERE grproj.dtcan IS NULL AND proj.dtcan IS NULL AND form.dtcan IS NULL ");
This is the example of my query with Linq, the quantity field should be a Count:
IList<GrupoProjetoEntity> grupos = (from grupoProjeto in session.Query<GrupoProjetoEntity>()
join projeto in session.Query<ProjetoEntity>() on grupoProjeto.Id equals projeto.cdgruproj.Id
join tipoProjeto in session.Query<TipoProjetoEntity>() on projeto.tpproj.TipoProjeto equals tipoProjeto.TipoProjeto
join projetoFormulario in session.Query<ProjetoFormularioEntity>() on
new { SiglaProjeto = projeto.sgproj, tpproj = projeto.tpproj.TipoProjeto }
equals new { SiglaProjeto = projetoFormulario.sgproj, tpproj = projetoFormulario.tpproj.TipoProjeto }
join formulario in session.Query<FormularioEntity>() on projetoFormulario.cdfrm.Id equals formulario.Id
select new GrupoProjetoEntity()
{
Id = grupoProjeto.Id,
DescricaoGrupoProjeto = grupoProjeto.DescricaoGrupoProjeto,
QuantidadeDeUsuarios = 0
}).ToList();
Very good Miguel, as slow as it was, the consultation worked.
– Igor Monteiro
What not... try to use
letto calculate the value ofCountbefore thenew... may be that when using the operatorCountwithin thenewhe’s doing several Count.– Miguel Angelo
You can also see which query is being generated and run in the database using some BD profiler.
– Miguel Angelo
So, the consultation in the bank is instantaneous, I think for the excess of joins I will try to use Let and I speak to you.
– Igor Monteiro
All right, if it gets any faster I’ll change the answer to make it as good as possible.
– Miguel Angelo
What would this query look like with Let? it serves to group?
– Igor Monteiro
letis just a variable in the middle of the query, which can be used later. I changed the answer, but check there. If it doesn’t work I go back to the way it was before.– Miguel Angelo
Not much has changed in speed, I think I’m going to leave for an HQL, or something faster. Thank you Miguel!!
– Igor Monteiro
As you mentioned HQL, I assume you’re using Nhibernate. There are ways to see the query it is running in BD(is in English)... so it is easier to know what is happening under the cloths.
– Miguel Angelo