Get total relationship items 1: N [closed]

2

I have two Product and Items tables - these tables have Parent / Child relationship respectively. I would like to know how do I get the total items from the Items table knowing that each customer can have more than one Order and that each order consists of several items? If possible, I would also like to know how to get the full value of the items.

I'm using EntityFramework with Code First. The query already has the Include but so far when adding the GroupBy + Count the result returned is the Pedios total (parent table).

I thank you for the force.

    
asked by anonymous 23.03.2016 / 03:55

1 answer

3

I'm assuming the following construction of your Models :

public class Produto
{
    [Key]
    public int ProdutoId { get; set; }

    [Required]
    public int Nome { get; set; }
    [Required]
    public decimal Preco { get; set; }

    public virtual ICollection<PedidoProduto> PedidoProdutos { get; set; } // Aqui seria sua relação de itens
}

public class Pedido
{
    [Key]
    public int PedidoId { get; set; }
    public int ClienteId { get; set; }

    public virtual Cliente Cliente { get; set; }

    public virtual ICollection<PedidoProduto> PedidoProdutos { get; set; }
}

public class PedidoProduto
{
    [Key]
    public int PedidoProdutoId { get; set; }
    public int PedidoId { get; set; }
    public int ProdutoId { get; set; }

    [Required]
    public int Quantidade { get; set; }

    public virtual Pedido Pedido { get; set; }
    public virtual Produto Produto { get; set; }
}
  

I would like to know how do I get the total items in the Items table knowing that each customer can have more than one Order and that each order consists of several items?

It can be done like this:

var pedido = db.Pedidos.FirstOrDefault(p => p.PedidoId == 1);
var itens = pedido.PedidoProdutos.Select(pp => pp.Produto).ToList();
  

If possible, I would also like to know how to get the total value of the items.

So:

var total = pedido.PedidoProdutos.Sum(pp => pp.Produto.Preco * pp.Quantidade);
    
23.03.2016 / 04:27