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);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM