Simon Simon - 7 months ago 13
SQL Question

Entity Framework : How can i translate group by to entity framework statement

SELECT
MAX([VersionCode]) AS VersionCode,
[PackageName]
FROM
[dbo].[Application]
GROUP BY
[PackageName]
ORDER BY
[VersionCode] DESC


This sql statement allows me to select the maximum version of an application by grouping.

I have difficulty to translate it to use Entity Framework, mainly in group by section:

GroupBy ( a=>a.PackageName )


Then I don't know how to get the Application by the highest version.

Answer

After you GroupBy, you need to project the output with Select. As you want the highest version, you use Max:

var results = db.Applications
    .GroupBy(a => a.PackageName)
    .Select(g => new 
    {
        PackageName = g.Key,
        Version = g.Max(a => a.VersionCode)
    });