EF 汇总函数使用注意事项Max()/Min()等

一、字符串类型最大值

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

[javascript] view plain copy print?
  1. //字符串最大值,是字典排序最后一个  
  2. string max1 = _context.students.Max(q => q.sname);  
  3. Console.WriteLine(max1);  
  4.   
  5. //字符串最大值,如果不存在返回null  
  6. string max2 = _context.students  
  7.     .Where(q => false)  
  8.     .Max(q => q.sname);  
  9. Console.WriteLine(max2);  
  10. Console.WriteLine(max2 == null); //True  
  11. Console.WriteLine(max2 == ""); //False  
//字符串最大值,是字典排序最后一个
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.数字类型最大值,和数据库字段排序最后一个相同,如果没有数据抛出异常。

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

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

  1. decimal deci2 = _context.scores.Where(q => false).Max(q => q.degree);  
  2.             Console.WriteLine(deci2);  
decimal deci2 = _context.scores.Where(q => false).Max(q => q.degree);
            Console.WriteLine(deci2);

解决方案1:

  1. //解决方案1,使用DefaultIfEmpty(),推荐  
  2. var query = _context.scores.Where(q => false)  
  3.     .Select(q => q.degree)  
  4.     .DefaultIfEmpty();  
  5. Console.WriteLine(query.ToString());  
  6. decimal deci3 = query  
  7.     .Max();  
  8. Console.WriteLine(deci3);  
//解决方案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:

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

解决方案3:

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

猜你喜欢

转载自www.cnblogs.com/cuihongyu3503319/p/9154831.html
EF
今日推荐