使用Entity Framework 4和Linq查询比较DateTime属性中的日期的简单方法

我正在尝试运行以下一些代码,但是通过不将我期望的实体交给我来进行比较失败。

它比较06/09/2011 12:25:00 06/09/2011 0:00:0006/09/2011 12:25:00 ,后者是我的数据库记录值。 这就是比较失败的原因,我没有得到我需要的记录。

我只是想比较日期是否匹配,我不关心时间。

 DateTime today = DateTime.Now.Date; var newAuctionsResults = repo.FindAllAuctions() .Where(a => a.IsActive == true || a.StartTime.Value == today) .ToList(); 

我怎样才能比较日期?

如果在.StartTime.Value部分使用.Date属性,我会得到一个exception:

LINQ to Entities不支持指定的类型成员“Date”。 仅支持初始化程序,实体成员和实体导航属性。

您可以使用个人成员:

 var newAuctionsResults = repo.FindAllAuctions() .Where(a => a.IsActive == true || (a.StartTime.Value.Year == todayYear && a.StartTime.Value.Month == todayMonth && a.StartTime.Value.Day == todayDay)) .ToList(); 

…或使用L2E中支持的任何其他方法/属性 。

您还可以在命名空间System.Data.Objects下使用EntityFunctions.TruncateTime()

防爆。

 db.Orders.Where(i => EntityFunctions.TruncateTime(i.OrderFinishDate) == EntityFunctions.TruncateTime(dtBillDate) && i.Status == "B") 

像魅力一样工作。

尝试

 DateTime todayStart = DateTime.Now.Date; DateTime todayEnd = DateTime.Now; var newAuctionsResults = repo.FindAllAuctions() .Where(a => a.IsActive == true || (a.StartTime.Value >= todayStart && a.StartTime.Value <= todayEnd)) .ToList(); 

你可以转换使用

 DateTime.ToShortDateString() 

http://msdn.microsoft.com/en-us/library/system.datetime.toshortdatestring.aspx

这会忽略时间。

然后比较两个字符串。

 if(string1 == string2) { //Do Something }