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

后端 未结 10 2149
旧时难觅i
旧时难觅i 2020-12-13 05:16

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;

10条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-13 05:57

    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.

    int maxAge = _dbContext.Persons
      .OrderByDescending(p => p.Age)
      .Select(p => p.Age)
      .FirstOrDefault();
    

提交回复
热议问题