且构网

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

简单的方法使用实体框架4和LINQ查询比较datetime属性日期

更新时间:2023-01-29 10:20:23

您可以使用个人会员:

  VAR newAuctionsResults = repo.FindAllAuctions()
。凡( A => a.IsActive ==真
||(a.StartTime.Value.Year == todayYear
和;&安培; a.StartTime.Value.Month == todayMonth
和;&安培; a.StartTime.Value.Day == todayDay))
.ToList();



...或使用任何的 /en-us/library/bb738681.aspx\">the其他方法/属性。


I'm trying to run the following bit of code, but the comparison fails by not handing my the entities I expect it to.

It's comparing 06/09/2011 0:00:00 to 06/09/2011 12:25:00, the latter being my databases record value. So that's why the comparison is failing and I'm not getting the records I need.

I'm just trying to compare if the dates match up, I'm don't care about the time.

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

How can I compare only the dates?

If use the .Date property in the .StartTime.Value part, I get an exception:

The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

You can use the individual members:

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

...or use any of the other methods/properties supported in L2E.