How to get max value of a column using Entity Framework?

int maxAge = context.Persons.Max(p => p.Age); 

The version above, if the list is empty:

  • Returns null ― for nullable overloads
  • Throws Sequence contains no element exception ― for non-nullable overloads

_

int maxAge = context.Persons.Select(p => p.Age).DefaultIfEmpty(0).Max(); 

The version above handles the empty list case, but it generates more complex query, and for some reason doesn't work with EF Core.

_

int maxAge = context.Persons.Max(p => (int?)p.Age) ?? 0; 

This version is elegant and performant (simple query and single round-trip to the database), works with EF Core. It handles the mentioned exception above by casting the non-nullable type to nullable and then applying the default value using the ?? operator.


If the list is empty I get an exception. This solution will take into account this issue:

int maxAge = context.Persons.Select(p => p.Age).DefaultIfEmpty(0).Max();

Or you can try this:

(From p In context.Persons Select p Order By age Descending).FirstOrDefault

Try this int maxAge = context.Persons.Max(p => p.Age);

And make sure you have using System.Linq; at the top of your file