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();
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.
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.
You should use the TruncateTime
function:
EntityFunctions.TruncateTime(x.DateCreated)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With