Inside a compiled LINQ query as a condition part, I was using Datetime.Now . It used to give me irrelevant results. I think it used to store same Datetime.Now value for few subsequent calls. To solve this issue I send Datetime.Now as a value parameter to the compiled query and it is working fine.
Old Code
event.EventEnd >= Datetime.Now
New Code
event.EventEnd >= currentTime
Where currentTime is a variable contains Datetime.Now value received outside from compiled query.
Please let me know if this is the default behavior of complied LINQ query or I was wrong somewhere
Platform : ASP.NET 4.0, MVC 2.0
Irrelevant results means , say we have one record with eVent.EventEnd value is 10-10-10 02:10 PM , if I run the query at 10-10-10 02:00 PM , we get that record in the result. If I run the query at 10-10-10 03:00 PM also we get that record in result. Which is wrong. But after I use the variable instead on DateTime.Now , it is working fine.
Compiled LINQ Query
public 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
})
);
I saw the same issue. I verified using SQL Profiler that it had cached the value of
DateTime.Now.