且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在实体框架中找到具有指定日期范围列表的日期?

更新时间:2023-01-29 22:36:21

你可以使用 LinqKit 为此:

  var expr = PredicateBuilder.False< Deal>(); 
foreach(条件中的var范围.DateRanges)
expr = expr.Or(d => dt.CloseDate> = range.Start&& dt.CloseDate< range.End);
deals = deals.AsExpandable()。Where(expr);

另一个选项是使用表达式树,但这似乎有点过分的你想要做的。


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)));

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?

You can use LinqKit for this:

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.