Select all items with same Id in the same table

Asked

Viewed 203 times

1

Very well, I will try to be as clear as possible. I have the stock table where will have there several products -> Productoid and its Quantity. In the same table the product can be repeated with a different quantity, in my current code I can only take the first quantity in the table but I can’t take the other and add the two. use Entity framework using lambda.

inserir a descrição da imagem aqui

            Estoque estoque = db.Estoque.Where(x => x.ProdutoId == model.ProdutoId).FirstOrDefault();
        int qtdEstoque = estoque.Quantidade;

Returns =10 and had to be Quantity = 30

1 answer

1


You won’t be able to add up the two quantities that way, the best way to solve this would be, instead of using the FirstOrDefault(), use the ToList()to make the query, thus creating a Inventory List of the same Produto Id.So work with that list, make one ForEach in it and add the Amounts. Something like this:

var estoques = db.Estoque.Where(x => x.ProdutoId == model.ProdutoId).ToList();

int quantidadeEstoque = 0;

foreach(var estoque in estoques){
            quantidadeEstoque += estoque.Quantidade;
};

That way you can take all the stocks with the least Produto_Id.

  • 1

    Thanks, that’s exactly what I needed, I had managed to do using an ugly gambiara here, but your code got cleaner.vlw

Browser other questions tagged

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