How to mount SELECT in lambda C#?

Asked

Viewed 493 times

4

I recently asked for help to assemble a SELECT to bring the price of products

How to mount SELECT

They gave me this solution that worked perfectly:

SELECT P.PROCODIGO, P.PRONOME, H.HISPRECO
FROM PRODUTO P
INNER JOIN HISTORICO H ON P.PROCODIGO = H.PROCODIGO
WHERE H.HISDATA = (SELECT MAX(HISDATA) FROM HISTORICO WHERE PROCODIGO = P.PROCODIGO)

But now I need to mount that same SELECT in lambda with C#, because I started using Entity. Can someone help me?

Thank you!

1 answer

6


Would look like this:

var produtos = db.Historicos
                 .Include(h => h.Produto)
                 .OrderByDescending(h => h.HistoricoData)
                 .GroupBy(h => h.ProdutoId)
                 .Select(group => group.FirstOrDefault())
                 .ToList();

In the Entity Framework one should not think like in SQL. The way of doing things is different. The generated SQL will possibly not be equal, but the result will be.

  • Got it, but in case I’m using repository of the working drive, it makes a difference?

  • 1

    Faz: http://answall.com/a/80696/2999

  • I am trying to create a method in my Object, but Include asks for a string path. In case History should be a Dbset<Historico>?

  • It can be a string or an Expression. Do not use EF repository. You read the link I sent you?

  • Yes, but my project is already set up with Reset and work unit so for now I will not change. But in my include does not accept Expression, db in case is a Dbcontext?

  • Well, you will be working with limitations and your project will soon have problems by your decision. I would accept the Include if you had done it the right way. db is a DbContext.

  • I’m going to change my project, I just need to read better what you gave me and study some more. But I had to do with the Select, thank you so much for your help!

Show 2 more comments

Browser other questions tagged

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