For subtracting two dates, use LINQ to Entities.

datetime entity-framework linq-to-entities

Question

I'm attempting to use LINQ and Entity Framework to calculate the number of days between two dates. It is informing me that the System's Subtract function is not recognized. SpanTime class

This is my LINQ query's where section.

where ((DateTime.Now.Subtract(vid.CreatedDate).TotalDays < maxAgeInDays))

The error I encounter in the VS.NET debugger is shown here.

{"LINQ to Entities does not recognize the method 'System.TimeSpan Subtract(System.DateTime)' method, and this method cannot be translated into a store expression."}

Is there a better method to get the number of days between two DateTimes in the entity framework or am I doing something incorrectly?

thanks Michael

1
60
3/31/2011 7:09:17 AM

Accepted Answer

Here's how I made it work.

I created a datetime variable to denote the most recent date.

DateTime oldestDate = DateTime.Now.Subtract(new TimeSpan(maxAgeInDays, 0, 0, 0, 0));
...

then I changed the LINQ query's where clause.

where (vid.CreatedDate >= oldestDate )

worked well; many thanks to Micah for making me consider the expression tree.

43
3/31/2011 7:09:40 AM

Popular Answer

The correct response is preferable in this instance, but as a point of reference, you can conduct operations on dates and other objects using the EntityFunctions class.

where (vid.CreatedDate >= EntityFunctions.AddDays(DateTime.Now, -maxAgeInDay))


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