Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare Just Date Part of 2 DateTime Variables in LINQ with EF

Problem: I have a search form that allows users to search for something where the record date falls between 2 dates (mm/dd/yyyy)

All of the records and objects are of type Datetime but all I need to compare is the date parts not the time part.

According to MSDN, the Date property is supported in LINQ however this statement as written will not allow me to append .Date to the lambda part:

Error:

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

Example:

x.DateCreated.Date

I am sure this problem comes up a lot - How do I solve it?

I guess I could pad the other date by appending 23:59:59 = 86399 secs to the <= part

Here is the statement. (db is a context object)

 model.Contacts = 
                db.Prospects.Where(x => x.DateCreated >= df.Date && x.DateCreated <= dt.Date)
                    .OrderByDescending(x => x.DateCreated)
                    .Take(100)
                    .ToList();
like image 962
Slinky Avatar asked Jul 11 '13 11:07

Slinky


People also ask

How do I check if one date is greater than another in C#?

Compare() Method in C# This method is used to compare two instances of DateTime and returns an integer that indicates whether the first instance is earlier than, the same as, or later than the second instance.

What does Dbfunctions TruncateTime do?

TruncateTime(Nullable<DateTime>) When used as part of a LINQ to Entities query, this method invokes the canonical TruncateTime EDM function to return the given date with the time portion cleared.


2 Answers

You should use the TruncateTime function:

EntityFunctions.TruncateTime(x.DateCreated) 
like image 121
Magnus Avatar answered Oct 23 '22 12:10

Magnus


You should use DbFunctions.TruncateTime() in the Entity Framework version 6.

var fromDate = criteria.FromCreatedDate.Value.Date;
items.Where(i => DbFunctions.TruncateTime(i.CreatedOnDate) >=fromDate);

To get all items whose date is greater than fromdate ignoring the timepart.

Thanks @gor.

like image 42
Ram Avatar answered Oct 23 '22 14:10

Ram