I'm using LINQ->WCF Data Services->EF, which supports a subset of LINQ with a few caveats. I've had no trouble with that once learning the tricks and workarounds for various things, but I'd like to make a reusable expression generator for comparing only the Date
portion of a DateTime
.
With regular EF you can use EntityFunctions.TruncateTime
(EF<6) or DbFunctions.TruncateTime
(EF6+), but this doesn't work over data services.
My solution so far has been to repeatedly build this mess of a where clause:
.Where(x => x.DateProperty.Year == DateToCompare.Year &&
x.DateProperty.Month == DateToCompare.Month &&
x.DateProperty.Day == DateToCompare.Day);
That's just nasty to have to repeatedly write (but it works), so I was trying to create something like:
.WhereDate(x => x.DateProperty, DateToCompare);
Anything similar would do, just short and sweet and readable - I detest repetitive unnecessary-feeling code.
The structure isn't a problem, I know I need something that takes IQueryable<T>
, Func<T, DateTime>
(or Expression<Func<T, DateTime>>
), and DateTime
and returns IQueryable<T>
.
public static IQueryable<T> WhereDate<T>(this IQueryable<T> data, Func<T, DateTime>> selector, DateTime date)
{
return data.Where(/*Something*/);
};
Where I'm having trouble is taking this and building an expression that can be put into that where clause without violating the restrictions of expression trees. I'm not entirely sure how to take an existing query and add my own where statement to the expression without doing a .Where
, which I think might be the key here. I think I need to take in an Expression<Func<T, DateTime>>
and build something that uses that to add an Expression<Func<T, bool>> to the tree and return it as an
IQueryable`.
Anybody got some experience with this, or know which docs I should be reading?
The biggest barriers here are that you can't turn a statement-based lambda into an expression, and you can't pass unsupported functions into the data service or EF. This makes all of the naïve solutions impossible, and as far as I know leaves manual expression manipulation.