I need to build a “between” function to check if a date is included in a range of 2 dates. I wrote this, but it doesn’t work:
private static Expression<Func<TElement, bool>> IsDateBetween<TElement>(Expression<Func<TElement, object>> valueSelector, DateTime date)
{
var p = valueSelector.Parameters.Single();
var after = Expression.LessThanOrEqual(
Expression.Property(valueSelector.Body, "FromDate"), Expression.Constant(date.Date, typeof(DateTime)));
var before = Expression.GreaterThanOrEqual(
Expression.Property(valueSelector.Body, "ToDate"), Expression.Constant(date.Date, typeof(DateTime)));
Expression body = Expression.And(after, before);
return Expression.Lambda<Func<TElement, bool>>(body, p);
}
I call it in this way:
DataContext.EventHistories.Where(IsDateBetween<EventHistory>(h => new { h.FromDate, h.ToDate }, dateInTheMiddle))
I must use this way because date not supported in linq entities.
Thanks
You could try something like that
usage
but it’s quite complicated to do
EDIT
Well, to simulate the
DateTime.Date, you could do :Or create an interface
and an extension method
usage :