问题描述
我创建了一个包含日期范围的类的 IEnumerable.该类如下所示:
I have an IEnumerable of a class that I created to contain date ranges. That class looks like this:
public class Range<T>
where T: struct
{
public T Start { get; set; }
public T End { get; set; }
}
我想在我的集合中查找日期列在任何指定日期范围内的所有记录.这是我的尝试:
I want to find all the records in my set where a date column falls within ANY of the specified date ranges. This was my attempt:
deals = deals.Where(
deal =>
criteria.DateRanges.Any(
dt =>
deal.CloseDate >= dt.Start &&
deal.CloseDate < dt.End.Value.AddDays(1)));
我认为这会引发一个错误,因为 EF 不知道如何将 criteria.DateRanges.Any()
转换为 SQL.那么,您将如何编写此代码来查找与任何日期范围匹配的日期?
This throws an error I assume because EF doesn't know how to translate criteria.DateRanges.Any()
to SQL. So how would you write this to find dates that match ANY of the date ranges?
推荐答案
你可以使用 LinqKit 为此:
var expr = PredicateBuilder.False<Deal>();
foreach(var range in criteria.DateRanges)
expr = expr.Or(d => dt.CloseDate >= range.Start && dt.CloseDate < range.End);
deals = deals.AsExpandable().Where(expr);
另一种选择是使用 表达式树 但这似乎是对于你想要做的事情有点矫枉过正.
Another option would be to use Expression Trees but that seems a bit overkill for what you're trying to do.
这篇关于如何在实体框架中查找具有指定日期范围列表的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!