Comparing date only on DateTime properties in EF4.
I find myself using the 'pattern' below rather unsettlingly often, when I want to select entities with based only on the date part of a DateTime property. EF doesn't parse the DateTime.Date property to T-SQL, so I end up using this code:
var nextDay = raceDate.Date.AddDays(1);
return EntityContext.RacingInfoes.SingleOrDefault(ri => ri.RaceDate >= raceDate && ri.RaceDate < nextDay);
It's the most readable solution I have found so far, but I don't like repeating it everywhere. However, I can't encapsulate it in any 开发者_如何学编程method as that method is not recognised by the Linq to Entities parser. Is there anything I can do about this?
You can encapsulate it by writing a method like this:
Expression<Func<T, bool>> OnDate<T>(Expression<Func<T, DateTime>> selector,
DateTime date)
{
var nextDay = date.Date.AddDays(1);
// Build up an expression tree, using Expression.AndAlso etc to
// compare the result of applying the selector with both date and nextDay
}
Then you'd write:
return EntityContext.RacingInfoes.SingleOrDefault(Helper.OnDate(x => x.RaceDate),
raceDate);
(OnDate
is a bad name, but you see what I mean...)
I use this (often in combination with LINQKit's Invoke functionality) (which is similar to an implementation of Jon Skeet's answer):
public static class Criteria
{
...
public static Expression<Func<DateTime, DateTime, bool>> IsOnDate =
(dateTime, onDate) =>
dateTime >= onDate.Date `&&` dateTime < onDate.AddDays(1).Date;
...
}
This way, you can combine the criteria with other conditions in a single statement
EntityContext.RacingInfoes.AsExpandable().SingleOrDefault(ri =>
Criteria.IsOnDate.Invoke(ri.RaceDate, DateTime.Today) || someOtherCriteria);
精彩评论