我尝试在60天内选择数据库中的记录,当前日期为30天,20天不同。
请参阅下面的查询。
var uploads = (
from files in _fileuploadRepository.Table
join product in _productRepository.Table on files.Event equals product.Id
where
(
product.EventDate != null &&
(product.EventDate.Subtract(DateTime.Now).Days <= 60 && product.EventDate.Subtract(DateTime.Now).Days >= 60) ||
(product.EventDate.Subtract(DateTime.Now).Days <= 30 && product.EventDate.Subtract(DateTime.Now).Days >= 30) ||
(product.EventDate.Subtract(DateTime.Now).Days <= 20 && product.EventDate.Subtract(DateTime.Now).Days >= 20))
&&
files.IsSkiped == false
select files;
).ToList();
但此查询发生错误。
我很无能为力。请帮助。
答案 0 :(得分:53)
您可以使用EntityFunctions.DiffDays
方法
EntityFunctions.DiffDays(product.EventDate, DateTime.Now) //this will return the difference in days
<强>更新强>
EntityFunctions现在已经过时,所以你应该使用DBFunctions。
System.Data.Entity.DbFunctions.DiffDays(product.EventDate, DateTime.Now)
答案 1 :(得分:34)
最简单的方法是在执行查询之前计算出的边界:
// Only evaluate DateTime.Now once for consistency. You might want DateTime.Today instead.
DateTime now = DateTime.Now;
DateTime nowPlus60Days = now.AddDays(60);
DateTime nowPlus30Days = now.AddDays(30);
DateTime nowPlus20Days = now.AddDays(20);
var query = ...
where product.EventDate <= nowPlus60Days
...
请注意,您当前的查询甚至没有意义,因为每个“或”'d子句都声明给定的计算小于或等于值和大于或等于等于相同的值。如果你想要简单的“等于”,那就用它吧。如果没有,则不清楚 试图做什么。
如果您要将值设置为“小于20”,“20-30”,“30-60”,“超过60”,则需要使用某种形式的分组。
答案 2 :(得分:4)
这应该有效:
using System.Data.Entity.SqlServer;
where (int)SqlFunctions.DateDiff("day", product.EventDate, DateTime.Now) <= 60
答案 3 :(得分:3)
要添加scartag的答案,
MSDN documentation for DbFunctions.DiffDays没有直接提及DiffDays()返回的值是否以及何时为负,所以我认为我在这里提供了这些信息:
当参数1日期大于(即将来相对于)参数2日期时,结果将为负。
例如,给定一个带有非空字段Deliveries
的表ScheduledDeliveryDate
,该表可以在过去和将来相对于当前日期具有值,此查询将获得所有记录在当前日期/时间(过去和未来)的2天内交货日期/时间:
DateTime now = DateTime.Now;
var results = from d in Deliveries
where (DbFunctions.DiffDays(d.ScheduledDeliveryDate, now) < 2
&& DbFunctions.DiffDays(d.ScheduledDeliveryDate, now) > -2)
select d;