如何在实体框架中找到具有指定日期范围列表的日期? [英] How to find a date with a list of specified date ranges in Entity Framework?

查看:173
本文介绍了如何在实体框架中找到具有指定日期范围列表的日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我创建的类的IEnumerable来包含日期范围。该类看起来像这样:

  public class Range< T> 
其中T:struct
{
public T Start {get;组; }
public T End {get;组; }
}

我想查找我的集合中所有记录,在任何指定的日期范围内。这是我的尝试:

  deals = deals.Where(
deal =>
criteria.DateRanges .Any(
dt =>
deal.CloseDate> = dt.Start&&
deal.CloseDate< dt.End.Value.AddDays(1)))

这会引发一个错误,因为EF不知道如何翻译 criteria.DateRanges.Any()到SQL。那么你怎么写这个来找到与任何日期范围相匹配的日期?

解决方案

你可以使用 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.

这篇关于如何在实体框架中找到具有指定日期范围列表的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆