Yuc*_*cel 103 c# linq datetime entity-framework
在我的应用程序中,我使用的是实体框架.
我的表
-Article
-period
-startDate
Run Code Online (Sandbox Code Playgroud)
我需要匹配=>的记录 DateTime.Now > startDate and (startDate + period) > DateTime.Now
我试过这个代码,但现在正在运行
Context.Article
.Where(p => p.StartDate < DateTime.Now)
.Where(p => p.StartDate.AddDays(p.Period) > DateTime.Now)
Run Code Online (Sandbox Code Playgroud)
当我运行我的代码时,会发生以下异常
LINQ to Entities无法识别方法'System.DateTime AddDays(Double)'方法,并且此方法无法转换为商店表达式.
Jus*_*ner 192
使用LINQ to Entity Framework时,Where子句中的谓词将转换为SQL.你得到了这个错误,因为没有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);
Run Code Online (Sandbox Code Playgroud)
如果您使用的是.NET 4.0,还可以尝试使用EntityFunctions.AddDays方法:
Context.Article.Where(p => p.StartDate < DateTime.Now)
.Where(p => EntityFunctions.AddDays(p.StartDate, p.Period)
> DateTime.Now);
Run Code Online (Sandbox Code Playgroud)
注意:EF 6
现在就是System.Data.Entity.DbFunctions.AddDays
.
and*_*rew 87
我认为这是最后一个答案试图建议的,而不是试图为p.startdat添加天数(不能转换为sql语句的东西)为什么不做一些可以等同于sql的东西:
var baselineDate = DateTime.Now.AddHours(-24);
something.Where(p => p.startdate >= baselineDate)
Run Code Online (Sandbox Code Playgroud)