我正在尝试创建一种通用方法来查找日期属于用户指定日期范围列表的交易。这是我的代码:
public IQueryable<T> ApplyDateRanges<T>(IQueryable<T> query, Expression<Func<T, DateTime>> dateSelector, IEnumerable<Range<DateTime>> dates)
{
var enumerable = dates as Range<DateTime>[] ?? dates.ToArray();
Expression<Func<T, Range<DateTime>, bool>> matcher =
(row, rangeItem) => (rangeItem.Start == null || dateSelector.Invoke(row) >= rangeItem.Start) &&
(rangeItem.End == null || dateSelector.Invoke(row) < rangeItem.End.Value.AddDays(1));
var expr = PredicateBuilder.False<T>();
foreach (var dt in enumerable)
{
expr = expr.Or(d => matcher.Invoke(d, dt));
}
return query.AsExpandable().Where(expr.Expand());
}
_helperService方法:
The parameter 'deal' was not bound in the specified LINQ to Entities query expression.
但我收到错误:$ vagrant box list
造成这种情况的原因是什么?
答案 0 :(得分:1)
异常消息表明dateSelector
参数未正确反弹。由于涉及第三方包,我无法分辨是什么导致了它。
但我想这与你的previous question有关。我打算建议你另一个简单的手动表达式构建工作解决方案,不涉及第三方包。在这里(假设Range
类Start/End
成员的类型为DateTime?
):
public static class QueryableExtensions
{
public static IQueryable<T> WhereIn<T>(IQueryable<T> source, Expression<Func<T, DateTime>> dateSelector, IEnumerable<Range<DateTime>> ranges)
{
var filter = ranges == null ? null : ranges.Select(range =>
{
var startFilter = range.Start != null ? Expression.GreaterThanOrEqual(dateSelector.Body, Expression.Constant(range.Start.Value.Date)) : null;
var endFilter = range.End != null ? Expression.LessThan(dateSelector.Body, Expression.Constant(range.End.Value.Date.AddDays(1))) : null;
return startFilter == null ? endFilter : endFilter == null ? startFilter : Expression.AndAlso(startFilter, endFilter);
})
.Where(item => item != null)
.Aggregate(Expression.OrElse);
return filter != null ? source.Where(Expression.Lambda<Func<T, bool>>(filter, dateSelector.Parameters[0])) : source;
}
}
你可以像这样使用它(不需要辅助服务实例,遵循LINQ精神):
var deals = dbContext.Deals.WhereIn(deal => deal.ClosedDate, closeDates);