你可以尝试类似的东西
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));