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

asp.net-mvc-3 c# entity-framework

Question

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();
1
9
7/11/2013 11:21:56 AM

Popular Answer

You should use the TruncateTime function:

EntityFunctions.TruncateTime(x.DateCreated) 
14
7/11/2013 11:27:59 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow