LINQ到的EntityFramework日期时间 [英] Linq to EntityFramework DateTime
问题描述
在我的应用我使用实体框架。
In my application I am using Entity Framework.
我的表
-Article
-period
-startDate
我需要匹配=> DateTime.Now&GT的记录;的startDate和(+的startDate期)GT; DateTime.Now
我想这code,但其现在的工作。
I tried this code but its now working
Context.Article
.Where(p => p.StartDate < DateTime.Now)
.Where(p => p.StartDate.AddDays(p.Period) > DateTime.Now)
当我运行我的code异常(LINQ到实体无法识别方法的System.DateTime AddDays(双人间)的方法,而这种方法不能被翻译成店前pression)发生。
When I run my code Exception (LINQ to Entities does not recognize the method 'System.DateTime AddDays(Double)' method, and this method cannot be translated into a store expression.) occur.
推荐答案
在使用LINQ to实体框架,里面的你predicates Where子句会转换为SQL。你得到的错误,因为没有转换为SQL的 DateTime.Add()
这是有道理的。
When using LINQ to Entity Framework, your predicates inside the Where clause get translated to SQL. You're getting that error because there is no translation to SQL for DateTime.Add()
which makes sense.
一个快速的解决方法将是读取第一个结果Where语句到内存中,然后使用LINQ到对象完成过滤:
A quick work-around would be to read the results of the first Where statement into memory and then use LINQ to Objects to finish filtering:
Context.Article.Where(p => p.StartDate < DateTime.Now)
.ToList()
.Where(p => p.StartDate.AddDays(p.Period) > DateTime.Now);
还可以如果正在使用4.0 .NET尝试 EntityFunctions.AddDays 方法
Context.Article.Where(p => p.StartDate < DateTime.Now)
.Where(p => EntityFunctions.AddDays(p.StartDate, p.Period)
> DateTime.Now);
注: EF 6
这是现在的<$c$c>System.Data.Entity.DbFunctions.AddDays$c$c>.
这篇关于LINQ到的EntityFramework日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!