2 回答

TA貢獻2065條經驗 獲得超14個贊
實際上支持DateTime.AddHours方法的翻譯。
問題是目前 EF Core 無法翻譯 的大部分(如果不是全部)成員DateTimeOffset,在這種特殊情況下 -DateTime屬性(與 等相同Offset)DateTimeUtc。
幸運的是它確實支持DateTimeOffset比較的轉換,所以解決方案是換一種方式——將DateTime參數(shù)轉換為DateTimeOffset并在查詢中進行簡單的比較,例如
if (startDate != null)
{
// Note: must be a variable outside the query expression tree
var startDateOffset = new DateTimeOffset(startDate.Value);
items = items.Where(i => i.DateCreated >= startDateOffset);
}

TA貢獻1719條經驗 獲得超6個贊
更新的答案(EF Core):
根據此鏈接,DbFunctions
EF Core 當前不支持。
如果您想AddHour
使用 EF Core 進行調用,一種選擇是AddHour
在您的數(shù)據庫中定義為標量函數(shù),然后您可以在您的 LINQ 查詢中調用它。
本文檔解釋了如何完成:
在您的 DbContext 上聲明一個靜態(tài)方法并使用以下注釋對其進行注釋DbFunctionAttribute
:
public class MyDbContext : DbContext
{
[DbFunction]
public static int AddHours(DataTime source, int hours)
{
// you don't need any implementation
throw new Exception();
}
}
像這樣的方法會自動注冊。注冊后,對 LINQ 查詢中的方法的調用可以轉換為 SQL 中的函數(shù)調用:
items = items.Where(i =>
MyDbContext.AddHours(i.DateCreated, i.DateCreated.Offset.Hours) >= startDate.Value);
免責聲明:我個人不喜歡這個解決方案。編寫一個新方法,只是為了拋出一個異常,遠不是一個優(yōu)雅的設計。不幸的是,如果您想使用 EF Core,您沒有太多選擇。
原始答案(EF 4/5/6):
AddHour不是您數(shù)據庫中的函數(shù)。它需要被翻譯成數(shù)據庫中相應的功能。
如果您使用的是 SQL Server,那么您可以使用這段代碼,它將轉換AddHour為相應的 DB 函數(shù):
items = items.Where(i =>
DbFunctions.AddHour(i.DateCreated, i.DateCreated.Offset.Hours) >= startDate.Value);
如果您不使用 SQL Server,那么您需要AddHour在您的數(shù)據庫中定義函數(shù),定義后您可以使用DbFunctions.AddHour, 來調用它。
- 2 回答
- 0 關注
- 125 瀏覽
添加回答
舉報