ProfK
ProfK

Reputation: 51064

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?

Upvotes: 0

Views: 226

Answers (2)

Jeff
Jeff

Reputation: 36573

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);

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500873

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...)

Upvotes: 1

Related Questions