LINQ to Entities for subtracting 2 dates

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


在这种情况下,接受的答案是更好的,但为了参考,您可以使用EntityFunctions类对日期执行操作等等。

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

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 can also use System.Data.Objects.EntityFucntions :

currentDate = DateTime.Now;

...
where  EntityFunctions.DiffDays(currentDate, vid.CreatedDate) < maxAgeIdDays 

All functions from EntityFunctions are only for Linq-to-entities and are mapped to SQL functions.

链接地址: http://www.djcxy.com/p/37646.html

上一篇: 如何对渴望获取进行排序和过滤

下一篇: LINQ to Entities用于减去2个日期