.net 如何在 LINQ to Entity 中的两个日期之间搜索?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2739485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 14:13:49  来源:igfitidea点击:

How to search between two dates in LINQ to Entity?

.netlinqlinq-to-entities

提问by Hrom

I have an example in SQL how to use the same logic in Linq to Entity?

我在 SQL 中有一个示例,如何在 Linq to Entity 中使用相同的逻辑?

SELECT * FROM TABLE WHERE DATE BETWEEN STARTDATE AND ENDDATE 

回答by spender

I'm assuming C#.

我假设 C#。

DateTime startDate=bla;
DateTime endDate=blabla;
using(var db=new MyDataContext())
{
    var filteredData=db.TABLE.Where(t => t.DATE > startDate && t.DATE < endDate);
    //...
}

回答by Dave Cousineau

You will want it to be inclusive on the start date, but exclusiveon the end date. This is because a DateTimeused as a date is really the very beginning of that day, and doesn't extend to the end of the day.

你会希望它是包容性的开始日期,而独家的结束日期。这是因为DateTime用作日期的 a 实际上是那天的开始,并且不会延伸到一天的结束。

// dates that are inclusive on the date range
var startDate = new DateTime(2016, 1, 1);
var endDate = new DateTime(2016, 12, 31);

...

// WRONG: this will ignore data on the last day
.Where(obj => obj.StartDate >= startDate && obj.EndDate <= endDate)

// RIGHT: this will include the last day
var endDateExclusive = endDate.AddDays(1);

...

.Where(obj => obj.StartDate >= startDate && obj.EndDate < endDateExclusive)

Even if you are using specific DateTimevalues, it can still be important to use >=and <, rather than >=and <=or >and <.

即使您使用特定DateTime值,使用>=and仍然很重要<,而不是>=and<=>and <

If you use both >=and <=signs, then two date ranges from X to Y and from Y to Z would both include records that exactly match Y. Depending on your requirements it could be a serious flaw to include the record in both date ranges. Similarly, if you use >and <, you would instead excluderecords from both date ranges that exactly matched Y.

如果同时使用>=and<=符号,则从 X 到 Y 和从 Y 到 Z 的两个日期范围都包含与 Y 完全匹配的记录。根据您的要求,将记录包含在两个日期范围内可能是一个严重的缺陷。同样,如果您使用>and <,您将从两个日期范围中排除与 Y 完全匹配的记录。