A simple way to compare dates in a DateTime attribute using Entity Framework 4 and Linq queries

I try to run the next bit of code, but the comparison fails without passing my objects, which I expect.

It compares 06/09/2011 0:00:00 with 06/09/2011 12:25:00 , the last of which is the value of my database. Therefore, why the comparison does not work, and I do not get the necessary records.

I'm just trying to compare if the dates match, I 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 to compare only dates?

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

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

+8
c # datetime entity-framework-4
source share
4 answers

You can use individual elements:

 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 .

+16
source share

You can also use EntityFunctions.TruncateTime() under the System.Data.Objects namespace

Ref.

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

It works like a charm.

+11
source share

to try

 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(); 
-one
source share

You can convert using

 DateTime.ToShortDateString() 

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

It will neglect time.

Then compare the two lines.

 if(string1 == string2) { //Do Something } 
-2
source share

All Articles