2020/04/10

[EF] 使用 SqlFunctions.DatePart 解決 DataTime 日期格式化問題

環境

  • Entity Framework 6

問題

在 EF 要處理日期時間的特定格式,不能用 DateTime.ToString() 的方式來處理

例如:

var orders = context.Orders.Where(x => x.OrderDate.ToString("yyyy-MM").Equals("2020-04")).ToList();

執行會出現錯誤

System.NotSupportedException: LINQ to Entities does not recognize the method 'System.String ToString(System.String)' method, and this method cannot be translated into a store expression.

因為 ToString() 是 C# 程式語法, SQL 不認識它是正常的

解決方法

透用 DbFunctionsSqlFunctions 來處理日期格式問題

以下是採用 SqlFunctions.DatePart() 來取得我要的日期部分

var orders = db.Orders.Where(x => 
                SqlFunctions.DatePart("year", x.OrderDate) == 2020 
             && SqlFunctions.DatePart("month", x.OrderDate) == 4
             ).ToList();

常用的 datepart 參數: year, month, day, week, hour, minute

詳細的 DatePart 可以查詢 SQL 文件: DATEPART

參考連結