views:

2580

answers:

4

I am trying to determine the number of days between 2 dates using LINQ with Entity Framework. It is telling me that it does not recognize Subtract on the System.TimeSpan class

Here is my where portion of the LINQ query.

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

Here is the error I receive in the VS.NET debugger

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

Am I doing something wrong or is there a better way to get the number of days between 2 DateTimes in the entity framework?

thanks Michael

+2  A: 

You run into these kind of isses because the predicate needs to be translated to an expression tree. And translation process doesn't recognize the DateTime.Now.Subtract method.

Micah
is there anyway to do what I am trying to do so that i can be translated into an expression tree?
+4  A: 

Here is how I got it to work

I defined a datetime variable that represents the oldest date

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

then I modified the where portion of the LINQ query

where (vid.CreatedDate >= oldestDate )

worked like a charm - thanks Micah for getting me to think about the expression tree

You should have flagged @Micah as answer and either add a comment to his response or update your question with the final answer.
ongle
A: 

thank you pal for the timeSpan oldDate solution ;-)! andrej

andy
A: 

The fact is that by design, LINQ to Entities needs to translate the whole query to SQL statements. That's where it cannot recognize Subtract method. It will occur whenever you try to use a C#/VB method inside a query. In these cases you have to figure out a way to bring out that part from the query. This post explains a bit more: http://mosesofegypt.net/post/LINQ-to-Entities-what-is-not-supported.aspx

Mahmoodvcs