How to make a SUM in different table fields in the Entity Framework?

Asked

Viewed 298 times

2

That’s the SQL that I have as an example, I would like to do the same with Linq?

select SUM(iv.precoMediano * oi.quantidade) as total from orc_orcamentoItem oi
inner join orc_insumoValor iv on oi.codigo = iv.codigoSinapi
where oi.grupoPai = 1 
group by oi.grupoPai

My main question in this is: How to do the Sum in English using Fields from both tables. For example: Sum(Tabela1=> Tabela1.quantity * table2.value)

Entities

Budget item

public int Item_id { get; set; }
public int Orcamento_id { get; set; }
public string Tipo_desc { get; set; }
public string Descricao { get; set; }
public int GrupoPai { get; set; }
public int Codigo { get; set; }
public decimal Quantidade { get; set; }
public string base_desc { get; set; }

Insumo Valor

public int InsumoDados_id { get; set; }
public int InsumoValor_id { get; set; }
public int CodigoSinapi { get; set; }
public string OrigemPreco { get; set; }
public decimal PrecoMediano { get; set; }
  • It would be nice for you to make available Models to have an answer very close to reality.

  • 1 Budget Item has 1 Input Value? what is the type of ratio?

  • Yes. They are linked by the code field.

  • My main question in this is: How to do the Sum in English using Fields from both tables. For example: Sum(Tabela1=> Tabela1.quantity * table2.value)

  • They are linked by the code field but for example an item has only one value? missed also put this in your models

  • 1

    Virgilio, thank you so much for your interest in helping. The Murarialex answer solved my problem.

Show 1 more comment

1 answer

2


Below is the version on LINQ and the tables I used in this example.

Query LINQ

var result = from oi in ctx.OrcamentoItem // onde ctx é o contexto do EF 
             join iv in ctx.InsumoValor on oi.Codigo equals iv.CodigoSinapi
             where oi.GrupoPai == 1
             group new { oi, iv } by oi.GrupoPai into grp
             select new
             {
                Total = grp.Sum(t => t.oi.Quantidade * t.iv.PrecoMediano)
             };

Classes

public class OrcamentoItem
{
    public int Item_id { get; set; }
    public int Orcamento_id { get; set; }
    public string Tipo_desc { get; set; }
    public string Descricao { get; set; }
    public int GrupoPai { get; set; }
    public int Codigo { get; set; }
    public decimal Quantidade { get; set; }
    public string base_desc { get; set; }
}

public class InsumoValor
{
    public int InsumoDados_id { get; set; }
    public int InsumoValor_id { get; set; }
    public int CodigoSinapi { get; set; }
    public string OrigemPreco { get; set; }
    public decimal PrecoMediano { get; set; }
}

See working on . NET Fiddle

  • 1

    Great. That’s just what I needed. Thanks.

Browser other questions tagged

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