Return the smallest value using the Entity Framework

Asked

Viewed 97 times

2

I’m quite inexperienced, that’s true, but I’ve grown a pair and I’ve come here to ask.. I’ve been stuck for a few hours on a solution that apparently would have everything to be simple, but I can’t see a way out.

I have two models, in one of them I have the basic product information (description, photo, etc) and in the other I have specific information of that package, as quantity in the package and price.

For example:

Product : Coca Cola 2 lts

Packings

UN:1 - 6.99

CX:12 - 83,88

I need to do a research that returns me the lowest price of packages registered by product.

The SQL would be this:

select DESCRICAO,
       (select min(PRECO)
        from PRODUTOEMBALAGEM
        where PRODUTO.ID = PRODUTOEMBALAGEM.IDPRODUTO) as PRECO
from PRODUTO
inner join PRODUTOEMBALAGEM on PRODUTO.ID = PRODUTOEMBALAGEM.IDPRODUTO
where IDESTABELECIMENTO = 1
group by PRODUTO.ID, PRODUTO.DESCRICAO

Normally I could use an expression like

contexto.ProdutoEmbalagens.Min(c => c.Preco)

However, I am trying to bring product information as well:

var produtos =
                    (from prod in contexto.Produtos
                     join emb in contexto.ProdutoEmbalagems on prod.Id equals emb.IdProduto
                     where prod.IdEstabelecimento == idEstabelecimento
                     select new
                     {
                         prod.Id,
                         prod.Descricao,
                         emb.Embalagem,
                         emb.Quantidade,
                         emb.Preco
                     }).ToList();

Any idea? I know for sure the solution is simple, but I’ve already fried my head :(

  • Make a query to return the packages registered by product, and with the return of this you perform the expression contexto.ProdutoEmbalagens.Min(c => c.Preco)

1 answer

2


Experiment as follows:

var produtos =  (from prod in contexto.Produtos
                 join emb in contexto.ProdutoEmbalagems on prod.Id equals emb.IdProduto
                 where prod.IdEstabelecimento == idEstabelecimento
                 select new
                 {
                     prod.Id,
                     prod.Descricao,
                     emb.Embalagem,
                     emb.Quantidade,
                     Preco = (contexto.ProdutoEmbalagens.Where(r => r.IdProduto == prod.Id).Min(c => c.Preco))
                 }).ToList();

Basically we’re using a SUBSELECT in LINQ.

Browser other questions tagged

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