我有一個問題,我想查詢的基礎上,日期時間只有一個的DateTimeOffset的SQL Server列的,我想知道是否有可能與EF之心做。
如果我在世界各地都有約會,并且我的業務邏輯將它們準確地記錄在他們本地的 DateTimeOffset 中,我希望能夠獲得特定日期的約會,而不管時區如何,但是,我得到一個例外,即查詢不能當我嘗試以下操作時翻譯:
public class Appointment
{
public int Id {get;set;}
public DateTimeOffset BeginTime {get;set;}
}
DateTime queryDay = new DateTime(2021, 1, 1);
var results = dbContext.Appointments.Where(a => a.BeginTime.DateTime >= queryDate && a.BeginTime.DateTime < queryDay.AddDays(1)).ToList();
有沒有辦法用 EF Core 做到這一點?我的意思是,在這個例子中,我只是想獲得一個特定的日期,但是,在現實中,我希望能夠做到這一點與任何時間值等任何日期時間
換句話說,我不打算按通用時間范圍進行過濾,而是按不考慮偏移的時間范圍進行過濾。
即使我創建了一個回傳 BeginTime.DateTime 的 [NotMapped] 屬性,它似乎也不起作用。
編輯:
確切的錯誤:
System.InvalidOperationException:無法翻譯 LINQ 運算式 'DbSet() .Where(t => True && t.BeginTime.DateTime >= __fakeStartDate_1 && t.BeginTime.DateTime < __fakeEndDate_2)'。以可翻譯的形式重寫查詢,或通過插入對“AsEnumerable”、“AsAsyncEnumerable”、“ToList”或“ToListAsync”的呼叫,顯式切換到客戶端評估。有關詳細資訊,請參閱https://go.microsoft.com/fwlink/?linkid=2101038。
uj5u.com熱心網友回復:
SqlServer 提供程式支持所謂的“雙重轉換”構造(首先到object,然后到其他型別,例如(DateTime)(object)),它欺騙 C# 編譯器接受通常會失敗的轉換(如果在 LINQ to Objects 背景關系中執行,則會失敗)和 EF Core翻譯器,強制后者使用operator發出從datetimeoffset到的轉換。datetime2 CAST
例如
var query = dbContext.Appointments
.Where(a => ((DateTime)(object)a.BeginTime) >= queryDate
&& ((DateTime)(object)a.BeginTime) < queryDate.AddDays(1));
成功地轉化為
DECLARE @__queryDate_0 datetime2 = '2021-01-01T00:00:00.0000000';
DECLARE @__AddDays_1 datetime2 = '2021-01-02T00:00:00.0000000';
SELECT [a].[Id], [a].[BeginTime]
FROM [Appointments] AS [a]
WHERE (CAST([a].[BeginTime] AS datetime2) >= @__queryDate_0) AND (CAST([a].[BeginTime] AS datetime2) < @__AddDays_1)
uj5u.com熱心網友回復:
有一種方式我不太喜歡,但它并沒有避免列上的索引,它應該可以作業。它會是這樣的:
public IEnumerable<Appointments> GetAppointments(DateTime start, DateTime end)
{
var bufferStart = start.AddDays(-1);
var bufferEnd = end.AddDays(1);
return dbContext.Appointments
.Where(a => a.BeginTime >= bufferStart && a.BeginTime < bufferEnd)
.AsEnumerable()
.Where(a => a.BeginTime.DateTime >= start && a.BeginTime.DateTime < end);
}
顯然,我不喜歡這個的原因有很多,所以仍在尋找更好的答案。如果有人有的話將不勝感激。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/344923.html
