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

后端 未结 10 2146
旧时难觅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:48
    maxAge = Persons.Max(c => c.age)
    

    or something along those lines.

    0 讨论(0)
  • 2020-12-13 05:50

    Your column is nullable

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

    Your column is non-nullable

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

    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

    SELECT 
        [GroupBy1].[A1] AS [C1]
        FROM ( SELECT 
            MAX([Extent1].[Age]) AS [A1]
            FROM [dbo].[Persons] AS [Extent1]
        )  AS [GroupBy1]
    

    Query with DefaultIfEmpty

    SELECT 
        [GroupBy1].[A1] AS [C1]
        FROM ( SELECT 
            MAX([Join1].[A1]) AS [A1]
            FROM ( SELECT 
                CASE WHEN ([Project1].[C1] IS NULL) THEN 0 ELSE [Project1].[Age] END AS [A1]
                FROM   ( SELECT 1 AS X ) AS [SingleRowTable1]
                LEFT OUTER JOIN  (SELECT 
                    [Extent1].[Age] AS [Age], 
                    cast(1 as tinyint) AS [C1]
                    FROM [dbo].[Persons] AS [Extent1]) AS [Project1] ON 1 = 1
            )  AS [Join1]
        )  AS [GroupBy1]
    
    0 讨论(0)
  • 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();
    
    0 讨论(0)
  • 2020-12-13 06:08

    Or you can try this:

    (From p In context.Persons Select p Order By age Descending).FirstOrDefault
    
    0 讨论(0)
  • 2020-12-13 06:09
    int maxAge = context.Persons.Max(p => p.Age);
    

    This version, 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();
    

    This version 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.

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

    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();
    
    0 讨论(0)
提交回复
热议问题