7
I have the following appointment at LINQ
var dados = _db.Contratos
.Where(a => a.Adesoes.Any(b => b.Pago))
.Select(a => new
{
Contrato = a.Numero,
ValorTASenior = a.Adesoes.Where(b => b.Pago).Sum(b => b.ValorTASenior),
ValorTAMaster = a.Adesoes.Where(b => b.Pago).Sum(b => b.ValorTAMaster),
ValorTAConsultor = a.Adesoes.Where(b => b.Pago).Sum(b => b.ValorTAConsultor),
ValorCliente = a.Adesoes.Where(b => b.Pago).Sum(b => b.ValorCliente)
});
I would like to know how I can simplify the summations of values and avoid the a.Adesoes.Where(b => b.Pago)
for every sum I need to make.
Entities & Context
public class MeuContext : DbContext
{
public DbSet<Contrato> Contratos { get; set; }
}
public class Contrato
{
[Key]
public int ContratoId { get; set; }
public int Numero { get; set; }
public virtual ICollection<Adesao> Adesoes { get; set; }
}
public class Adesao
{
[Key]
public int AdesaoId { get; set; }
public int ContratoId { get; set; }
public bool Pago { get; set; }
public int ValorTASenior { get; set; }
public int ValorTAMaster { get; set; }
public int ValorTAConsultor { get; set; }
public int ValorCliente { get; set; }
public virtual Contrato Contrato { get; set; }
}
you are not already doing this in your first Where ? . Where(a => a.Adesoes.Any(b => b.Paid))
– Marco Souza
Yes, but I’d like to avoid repeating that where for every sum.
– Pablo Tondolo de Vargas
I think I got the password. your problem is in your any ... your Where is satisfied with the first Paid Membership = true... you need your select to receive all Paid Memberships so you do not need the filter within select.
– Marco Souza
My Any guarantees that I only return contracts that have subscriptions in paid condition, but even then some contracts may have subscriptions paid and unpaid. So that’s why I do Where no select to add up only paid memberships.
– Pablo Tondolo de Vargas