Search code examples
c#linq.net-corequery-optimizationdatabase-performance

Linq - improve .Max()-query to execute everything inside the database instead of the C# app


The importent part of our DbVersion model looks like this:

    public class DatabaseVersion
    {
        .....
        public int Major { get; set; }
        public int Minor { get; set; }
        .....
        public Version Version => new Version(Major, MinorVersion);
    }

The Version property is not mapped to a database column but rather computed by the C# application. So a query to get the max version of the database looks like this:

context.DatabaseVersions.ToList().Max(x => x.Version) 

which is bad. It downloads all versions into memory and the looks for the latest version. I would like to improve this query but i am not able to write a linq query that gets the highest MajorVersion and for that the highest minor version.

How can that be done?


Solution

  • Correct order may help:

    var letest = context.DatabaseVersions
        .OrderByDescending(v => v.Major)
        .ThenByDescensing(v => v.MinorVersion)
        .Select(v => new Version(v.Major, v.MinorVersion))
        .FirstOrDefault();