在編譯的LINQ查詢中作爲條件部分,我使用了Datetime.Now。它曾經給我無關緊要的結果。我認爲它用於爲隨後的幾次調用存儲相同的Datetime.Now值。爲了解決這個問題,我將Datetime.Now作爲一個值參數發送到編譯後的查詢中,並且工作正常。Datetime.Now緩存在.NET編譯的LINQ查詢中
舊代碼
event.EventEnd >= Datetime.Now
新代碼
event.EventEnd >= currentTime
凡currentTime的是一個變量包含編譯的查詢之外接收Datetime.Now值。
請讓我知道這是符合LINQ查詢的默認行爲或我錯了地方
平臺:ASP.NET 4.0,MVC 2.0
不相關的結果的手段,說我們有一個記錄eVent.EventEnd值是10-10-10 02:10 PM,如果我在10-10-10 02:00 PM運行查詢,我們會在結果中獲得該記錄。如果我在10-10-10 03:00 PM運行查詢,我們也會得到結果中的記錄。這是錯誤的。但是,我在DateTime.Now上使用該變量後,它工作正常。
編譯LINQ查詢
在LINQ2SQLpublic static Func<DataContext, CommonParams, string, DateTime, IQueryable<EventEntity>> GetEventsByOwnerID
= CompiledQuery.Compile(
(DataContext context, CommonParams inputParams, string eventType, DateTime currentTime) =>
(from eVent in context.Events
join categories in context.Categories on eVent.CategoryID equals categories.CategoryID
where !eVent.IsDeleted
&& eVent.OwnerID == inputParams.UserID
&& (eventType == "ALL" ||
(eventType == "CURRENT" && eVent.EventEnd >= currentTime) ||
(eventType == "OLD" && eVent.EventEnd < currentTime))
orderby eVent.PostedOn descending
select new EventEntity()
{
EventID = eVent.EventID,
CategoryID = eVent.CategoryID,
Title = eVent.Title,
Owner = eVent.OwnerName,
EventStart = eVent.EventStart,
EventEnd = eVent.EventEnd,
Host = eVent.Host,
Location = eVent.Location,
Description = eVent.Description,
Email = eVent.Email,
URL = eVent.URL,
Phone = eVent.Phone,
CategoryName = categories.CategoryName,
ProgramName = eVent.ProgramName,
IsTelevised = eVent.IsTelevised,
ChannelName = eVent.ChannelName,
CityID = eVent.CityID,
CountryID = eVent.CountryID,
IsActive = eVent.IsActive,
OwnerID = eVent.OwnerID,
IsEndTimePartEmpty = eVent.IsEndTimePartEmpty,
IsStartTimePartEmpty = eVent.IsStartTimePartEmpty,
IsDeleted = eVent.IsDeleted,
ThumbnailURL = eVent.ThumbnailURL,
AttendeeCount = eVent.AttendeeCount,
CommentsCount = eVent.CommentsCount
})
);
你是什麼意思的無關結果?你能發佈整個查詢嗎?我想我們需要更多的信息。 – 2010-11-08 09:37:27
這是一個數據庫查詢嗎?它會使用數據庫服務器的日期和時間嗎?時鐘是否同步? – Rup 2010-11-08 09:47:03
@RUP,是的,數據庫服務器的時間是正確的。 – 2010-11-08 09:56:05