Search code examples
sqllinq-to-sqlsql-to-linq-conversion

SQL request to LINQ To SQL with aggregate function


I wrote the following basic SQL request, which returns the desired results :

SELECT c.IdC, MAX(v.[Date])
FROM TableV v
JOIN TableC c ON v.IdClassified = c.IdC
WHERE v.IdUser = 'MyIdUser'
GROUP BY c.IdC
ORDER BY MAX(v.[Date]) DESC, c.IdC

I'd like to "convert" it to LINQ, but I'm having hard times to deal with the aggregate function and the group by clause.

Any idea how to convert it to LINQ ?


Solution

  • Find an answer :

    var qViews = from v in dbContext.TableV
                 join c in dbContext.TableC ON v.IdC equals c.IdC
                 where v.IdUser == idUser
                 group v by v.IdC into grp
                 let tri = grp.Max(x => x.Date)
                 orderby tri descending
                 select new { x = grp.Key /*whatever else*/ };
    

    Hope it helps