一、字符串类型最大值

1.字符串类型的最大值,和数据库的字典排序最后一个相同,如果存在返回null

//字符串最大值,是字典排序最后一个
string max1 = _context.students.Max(q => q.sname);
Console.WriteLine(max1);

//字符串最大值,如果不存在返回null
string max2 = _context.students
    .Where(q => false)
    .Max(q => q.sname);
Console.WriteLine(max2);
Console.WriteLine(max2 == null); //True
Console.WriteLine(max2 == ""); //False

二、数字类型最大值

1.数字类型最大值,和数据库字段排序最后一个相同,如果没有数据抛出异常。

//数字类型,获取最大值为正序排列最后一个值
            decimal deci1 = _context.scores.Max(q => q.degree);
            Console.WriteLine(deci1);

数字类型,获取条件的数据不存在抛出异常
其他信息: 到值类型“System.Decimal”的强制转换失败,因为具体化值为 null。
结果类型的泛型参数或查询必须使用可以为 null 的类型。

decimal deci2 = _context.scores.Where(q => false).Max(q => q.degree);
            Console.WriteLine(deci2);
解决方案1:

//解决方案1,使用DefaultIfEmpty(),推荐
var query = _context.scores.Where(q => false)
    .Select(q => q.degree)
    .DefaultIfEmpty();
Console.WriteLine(query.ToString());
decimal deci3 = query
    .Max();
Console.WriteLine(deci3);

生成sql如下:


解决方案2:

//解决方案2,先判断再取值,执行两次数据库查询
decimal deci4 = 0;
if (_context.scores.Any())
{
    deci4 = _context.scores.Max(q => q.degree);
}
Console.WriteLine(deci4);
解决方案3:

//解决方案3,内存取最大值
decimal deci5 = _context.scores
    .Select(q => q.degree)
    .ToList()
    .Max();
Console.WriteLine(deci5);

更多:

EF中查看上下文执行的Sql语句

EF GroupBy多个字段

关于EF上线文异常问题整理


本文转载:CSDN博客