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

后端 未结 10 2158
旧时难觅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 06:13

    In VB.Net it would be

    Dim maxAge As Integer = context.Persons.Max(Function(p) p.Age)
    
    0 讨论(0)
  • 2020-12-13 06:15

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

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

    0 讨论(0)
  • 2020-12-13 06:15

    Maybe help, if you want to add some filter:

    context.Persons
    .Where(c => c.state == myState)
    .Select(c => c.age)
    .DefaultIfEmpty(0)
    .Max();
    
    0 讨论(0)
  • 2020-12-13 06:15

    As many said - this version

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

    throws an exception when table is empty.

    Use

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

    or

    int maxAge = context.Persons.Select(x => x.Age).DefaultIfEmpty(0).Max()
    
    0 讨论(0)
提交回复
热议问题