Linq to EntityFramework DateTime

时间:2010-11-10 15:51:02

标签: c# linq entity-framework datetime

在我的应用程序中,我使用的是Entity Framework。

我的表

-Article
-period
-startDate

我需要匹配=>的记录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)

当我运行我的代码时,会发生以下异常

  

LINQ to Entities无法识别方法'System.DateTime AddDays(Double)'方法,并且此方法无法转换为商店表达式。

4 个答案:

答案 0 :(得分:181)

使用LINQ to Entity Framework时,Where子句中的谓词将转换为SQL。您收到该错误是因为DateTime.Add()没有对SQL进行转换,这是有道理的。

快速解决方法是将第一个Where语句的结果读入内存,然后使用LINQ to Objects完成过滤:

Context.Article.Where(p => p.StartDate < DateTime.Now)
               .ToList()
               .Where(p => p.StartDate.AddDays(p.Period) > DateTime.Now);

如果您使用的是.NET 4.0,也可以尝试使用EntityFunctions.AddDays方法:

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

答案 1 :(得分:85)

我认为这是最后一个答案试图建议的,而不是试图为p.startdat添加天数(不能转换为sql语句的东西)为什么不做一些可以等同于sql的东西: / p>

var baselineDate = DateTime.Now.AddHours(-24);

something.Where(p => p.startdate >= baselineDate)

答案 2 :(得分:3)

如何从DateTime.Now减去2天:

Context.Article
.Where(p => p.StartDate < DateTime.Now)
.Where(p => p.StartDate > DateTime.Now.Subtract(new TimeSpan(2, 0, 0, 0)))

说实话,我不确定你想要达到的目标,但这可能有效

答案 3 :(得分:2)

如果您需要将表达式转换为SQL,则可以尝试使用

System.Data.Entity.Core.Objects.AddDays 方法

实际上已经过时,但它确实有效。 它应该被System.Data.Entity.DbFunctions.AddDays取代,但我找不到它......