Linq to EntityFramework DateTime [英] Linq to EntityFramework DateTime
问题描述
我的表
-Article
-period
-startDate
我需要匹配的记录=> DateTime.Now > startDate和(startDate + period)> DateTime.Now
我尝试过这个代码,但现在正在工作
Context.Article
.Where(p => p.StartDate< DateTime.Now)
.Where(p => p.StartDate.AddDays(p.Period )> DateTime.Now)
当我运行我的代码时,出现以下异常
LINQ to Entities不能识别System.DateTime AddDays(Double)方法,并且此方法无法转换为存储表达式。 >
当使用LINQ to Entity Framework时,Where子句中的谓词被转换为SQL。你收到这个错误,因为没有翻译为$ DateTime.Add()
这是有道理的。
快速解决方法是将第一个Where语句的结果读入内存,然后使用LINQ to Objects完成过滤:
Context.Article.Where(p => p.StartDate< DateTime.Now)
.ToList()
.Where(p => p.StartDate.AddDays(p.Period )> DateTime.Now);
您还可以尝试 EntityFunctions.AddDays 方法,如果您使用的是.NET 4.0:
Context.Article.Where(p => p.StartDate< DateTime.Now)
.Where(p => EntityFunctions.AddDays(p.StartDate,p.Period)
> DateTime.Now);
注意:在 EF 6
a href =http://msdn.microsoft.com/en-us/library/dn220066%28v=vs.113%29.aspx =noreferrer> System.Data.Entity。 DbFunctions.AddDays
。
In my application I am using Entity Framework.
My Table
-Article
-period
-startDate
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 does not recognize the method 'System.DateTime AddDays(Double)' method, and this method cannot be translated into a store expression.
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.
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);
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);
Note: In EF 6
it's now System.Data.Entity.DbFunctions.AddDays
.
这篇关于Linq to EntityFramework DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!