2020/04/10

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

markdown ### 環境 - 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 不認識它是正常的 ### 解決方法 透用 [DbFunctions](https://docs.microsoft.com/en-us/dotnet/api/system.data.entity.dbfunctions?view=entity-framework-6.2.0&WT.mc_id=DOP-MVP-5002629) 或 [SqlFunctions](https://docs.microsoft.com/en-us/dotnet/api/system.data.entity.sqlserver.sqlfunctions?view=entity-framework-6.2.0&WT.mc_id=DOP-MVP-5002629) 來處理日期格式問題 以下是採用 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](https://docs.microsoft.com/zh-tw/sql/t-sql/functions/datepart-transact-sql?view=sql-server-ver15&WT.mc_id=DOP-MVP-5002629) ### 參考連結 - [DbFunctions](https://docs.microsoft.com/en-us/dotnet/api/system.data.entity.dbfunctions?view=entity-framework-6.2.0&WT.mc_id=DOP-MVP-5002629) - [SqlFunctions](https://docs.microsoft.com/en-us/dotnet/api/system.data.entity.sqlserver.sqlfunctions?view=entity-framework-6.2.0&WT.mc_id=DOP-MVP-5002629) - [SqlFunctions.DatePart Method](https://docs.microsoft.com/en-us/dotnet/api/system.data.entity.sqlserver.sqlfunctions.datepart?view=entity-framework-6.2.0&WT.mc_id=DOP-MVP-5002629) - [SQL 文件 DATEPART](https://docs.microsoft.com/zh-tw/sql/t-sql/functions/datepart-transact-sql?view=sql-server-ver15&WT.mc_id=DOP-MVP-5002629) - [Linq Convert DateTime? to DateTime in ("dd/MM/yyyy")](https://forums.asp.net/t/1854597.aspx) - [EF DateTime格式化](https://xbuba.com/questions/51970339)