How to get max value of a column using Entity Fram

2020-02-07 19:18发布

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.?

9条回答
女痞
2楼-- · 2020-02-07 19:48

Maybe help, if you want to add some filter:

context.Persons
.Where(c => c.state == myState)
.Select(c => c.age)
.DefaultIfEmpty(0)
.Max();
查看更多
老娘就宠你
3楼-- · 2020-02-07 19:52

Or you can try this:

(From p In context.Persons Select p Order By age Descending).FirstOrDefault
查看更多
太酷不给撩
4楼-- · 2020-02-07 19:55
maxAge = Persons.Max(c => c.age)

or something along those lines.

查看更多
够拽才男人
5楼-- · 2020-02-07 20:03

In VB.Net it would be

Dim maxAge As Integer = context.Persons.Max(Function(p) p.Age)
查看更多
Ridiculous、
6楼-- · 2020-02-07 20:03

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]
查看更多
啃猪蹄的小仙女
7楼-- · 2020-02-07 20:03

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();
查看更多
登录 后发表回答