あなたはそのようなことを試すことができます
public static IQueryable<TElement> IsDateBetween<TElement>(this IQueryable<TElement> queryable,
Expression<Func<TElement, DateTime>> fromDate,
Expression<Func<TElement, DateTime>> toDate,
DateTime date)
{
var p = fromDate.Parameters.Single();
Expression member = p;
Expression fromExpression = Expression.Property(member, (fromDate.Body as MemberExpression).Member.Name);
Expression toExpression = Expression.Property(member, (toDate.Body as MemberExpression).Member.Name);
var after = Expression.LessThanOrEqual(fromExpression,
Expression.Constant(date, typeof(DateTime)));
var before = Expression.GreaterThanOrEqual(
toExpression, Expression.Constant(date, typeof(DateTime)));
Expression body = Expression.And(after, before);
var predicate = Expression.Lambda<Func<TElement, bool>>(body, p);
return queryable.Where(predicate);
}
利用方法
DataContext.EventHistories.WhereDateBetween(h => h.FromDate, h => h.ToDate, dateInTheMiddle));
しかし、それはかなり複雑です
var myDate = DateTime.Now();
var result = DataContext.EventHistories.Where(m => m.FromDate >= myDate && m.ToDate<=myDate );
編集
をシミュレートするには、次のDateTime.Date
ようにします。
var myDate = DateTime.Now.Date();
var res = histories.AsQueryable()
.Where(m =>
EntityFunctions.CreateDateTime(m.FromDate.Year, m.FromDate.Month, m.FromDate.Day, 0, 0, 0) >= DateTime.Now &&
EntityFunctions.CreateDateTime(m.ToDate.Year, m.ToDate.Month, m.ToDate.Day, 0, 0, 0) <= DateTime.Now)
またはインターフェイスを作成します
public interface IFromDateToDate
{
DateTime FromDate { get; set; }
DateTime ToDate { get; set; }
}
と拡張メソッド
public static IQueryable<T> WhereDatesBetween<T>(this IQueryable<T> queryable, DateTime myDate) where T : IFromDateToDate
{
myDate = myDate.Date;
return queryable.Where(m =>
EntityFunctions.CreateDateTime(m.FromDate.Year, m.FromDate.Month, m.FromDate.Day, 0, 0, 0) >= myDate &&
EntityFunctions.CreateDateTime(m.FromDate.Year, m.FromDate.Month, m.FromDate.Day, 0, 0, 0) <= myDate);
}
利用方法 :
DataContext.EventHistories.WhereDatesBetween(dateInTheMiddle));