Transcribe SELECT to LINQ query expression

Asked

Viewed 216 times

4

How can I reproduce the query then to LINQ expression?

SELECT nome_empresa, 
       Count(funcionarios.id_funcionario) AS qtdfuncionario, 
       Count(id_colaborador)              AS qtdcolaboradores 
FROM   empresas 
       JOIN funcionarios 
         ON funcionarios.id_empresa = empresas.id_empresa 
       LEFT JOIN colaborador 
              ON colaborador.id_funcionario = funcionarios.id_funcionario 
GROUP  BY nome_empresa

This is what I have done so far, but I have not yet achieved the result:

var resultado = from e in db.empresas
                join f in db.funcionarios on e.id_empresa equals f.id_empresa into eGroup
                from f in eGroup.DefaultIfEmpty()
                join c in db.colaborador on f.id_funcionario equals c.id_funcionario into eGroup2
                from c in eGroup.DefaultIfEmpty()
                select new 
                {
                    NomeEmpresa = e.nome_empresa,
                    CountFuncionario = e.funcionarios.Count,
                    Colaboradores = eGroup2.Count(t => t.id_colaborador != null)
                };
  • You are using Entity Framework?

  • Yes I am ultilizing

  • It would be interesting to post the code you have already done. As it stands, you are only asking for an answer without exerting effort to reach it.

1 answer

1


The reason I asked if you were using Entity Framework is precisely because of the approach. LINQ does not support Include, which is used to load the information in advance (Eager Load) and mount the joins in the best possible way. Facilitates readability and avoids confusion that may be arising in this LINQ expression you put in the question.

An alternative is to use expression methods (Expression Methods) instead of the LINQ itself. It would look like this:

var resultado = db.Empresas
                .Include(e => e.Funcionarios)
                .Select(e => new {
                    NomeEmpresa = e.NomeEmpresa, 
                    CountFuncionario = e.Funcionarios.Count(),
                    Colaboradores = e.Funcionarios.SelectMany(f => f.Colaborador).Count()
                }).ToList();
  • 1

    Thank you so much for the help, it was exactly what I needed!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.