Linq 到 EntityFramework 日期时间 [英] Linq to EntityFramework DateTime
问题描述
在我的应用程序中,我使用的是实体框架.
In my application I am using Entity Framework.
我的桌子
-Article
-period
-startDate
我需要匹配的记录 => DateTime.Now >startDate 和 (startDate + period) >日期时间.现在
I need records that match => DateTime.Now > startDate and (startDate + period) > DateTime.Now
我试过这段代码,但它现在可以工作了
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)
当我运行我的代码时发生以下异常
When I run my code the following exception occur
LINQ to Entities 无法识别System.DateTime AddDays(Double)"方法,并且该方法无法转换为存储表达式.
LINQ to Entities does not recognize the method 'System.DateTime AddDays(Double)' method, and this method cannot be translated into a store expression.
推荐答案
使用 LINQ to Entity Framework 时,Where 子句中的谓词被转换为 SQL.您收到该错误是因为没有对 DateTime.Add()
的 SQL 进行翻译,这是有意义的.
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 to Objects 完成过滤:
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);
如果您愿意,也可以尝试 EntityFunctions.AddDays 方法重新使用 .NET 4.0:
You could also try the EntityFunctions.AddDays method if you're using .NET 4.0:
Context.Article.Where(p => p.StartDate < DateTime.Now)
.Where(p => EntityFunctions.AddDays(p.StartDate, p.Period)
> DateTime.Now);
注意:在 EF 6
中,它现在是 System.Data.Entity.DbFunctions.AddDays
.
Note: In EF 6
it's now System.Data.Entity.DbFunctions.AddDays
.
这篇关于Linq 到 EntityFramework 日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!