To get maximum value of a column that contains integer, I can use the following T-SQL comand
SELECT MAX(expression )
FROM tables
WHERE predicates;
Is it possible to obtain the same result with Entity Framework.
Let's say I have the following model
public class Person
{
public int PersonID { get; set; }
public int Name { get; set; }
public int Age { get; set; }
}
How do I get the oldest person's age?
int maxAge = context.Persons.?
Maybe help, if you want to add some filter:
Or you can try this:
or something along those lines.
In VB.Net it would be
Your column is nullable
Your column is non-nullable
In both cases, you can use the second code. If you use
DefaultIfEmpty
, you will do a bigger query on your server. For people who are interested, here are the EF6 equivalent:Query without
DefaultIfEmpty
Query with
DefaultIfEmpty
Selected answer throws exceptions, and the answer from Carlos Toledo applies filtering after retrieving all values from the database.
The following one runs a single round-trip and reads a single value, using any possible indexes, without an exception.