How to bring other columns with Groupby with LINQ

Asked

Viewed 474 times

1

I have two tables:

1st Process containing Processoid and Situacaoprocessoid

2nd Situationthe process that contains Situationthe Process and Description

Models:

public class ProcessoModel
{
    public int? ProcessoId { get; set; }
    public int? SituacaoProcessoId { get; set; }
    public virtual SituacaoProcessoModel SituacaoProcesso { get; set; }

}

public class SituacaoProcessoModel
{
    public int? SituacaoProcessoId { get; set; }      
    public string Descricao { get; set; }
    public virtual List<ProcessoModel> LstProcesso { get; set; }
}

I want to bring the total count of processes for each type of situation, my code below is already doing this, but I want the Description column to come the Description column of the Situation table?

var processo = db.TbProcesso
            .GroupBy(p => p.SituacaoProcessoId)
            .Select(p => new
            {
                Descricao = p.Key,
                Total = p.Count()
            });

In my Sql I can, the problem is to do with LINQ

SELECT 
    sp.Descricao, COUNT(p.SituacaoProcessoId) AS Total
FROM
    processo p
        LEFT JOIN
    situacao_processo sp ON p.SituacaoProcessoId = sp.SituacaoProcessoId
GROUP BY p.SituacaoProcessoId

Upshot:

inserir a descrição da imagem aqui

  • Have you tried using the Join of Linq? Something like .Join(p.TbSituacaoProcesso, processo.SituacaoProcessoId, situacaoProcesso.SituacaoProcessoId, &#xA;(post, meta) => new { TbProcesso = post, TbSituacaoProcesso = situacaoProcesso })

  • Maurício, you can post the models Processo and SituacaoProcesso?

  • @Ricardo had tried some things but nothing went right

  • @LINQ Ready, posted the models.

1 answer

1


Just make use of the navigation properties.

var processo = Processos
                .GroupBy(p => new 
                             { 
                                 p.SituacaoProcessoId, 
                                 Descr = p.SituacaoProcesso.Descricao 
                              })
                .Select(p => new
                {
                    Descricao = p.Key.Descr,
                    Total = p.Count()
                });
  • It worked when I switched this part: p.Situacaoprocessoid, Descr = p.SituacaoProcesses.Description

  • I don’t get it, @Mauricioferraz

  • In his answer you put : p.Processoid, Descr = p.SituacaoProcesso.Descricao, there it did not work because it grouped by Processoid then I changed to p.Situacaoprocessoid, Descr = p.SituacaoProcesson.Descricao and then yes it worked, understood?

  • @Mauricioferraz ah, I was wrong to type

  • Corrected perfect Thank you.

Browser other questions tagged

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