【问题标题】:Comparing DateTime object in Linq比较 Linq 中的 DateTime 对象
【发布时间】:2016-03-30 15:16:08
【问题描述】:

我正在尝试创建一个 linq 查询以获取 1 年前的所有日期(预期 365 个值)

 using (var context = new Context1())
 {
      var query = (from c in context.Daily25Data
                   where c.Date > DateTime.Now.AddYears(-1)
                   select c).ToList();

                   Console.WriteLine(query);
 }

尝试使用上面的代码但出现异常

附加信息:LINQ to Entities 无法识别方法 'System.DateTime AddYears(Int32)' 方法,以及此方法 无法翻译成商店表达式。

【问题讨论】:

    标签: c# entity-framework linq datetime linq-to-entities


    【解决方案1】:

    您可以在执行查询之前将值提取到变量中:

    var oneYearEarlier = DateTime.Now.AddYears(-1);
    
    var query = (from c in context.Daily25Data
                 where c.Date > oneYearEarlier
                 select c).ToList();
    

    【讨论】:

      【解决方案2】:

      同意@RB 的回答。也可以使用DbFunctions.AddYears静态方法:

      var query = (from c in context.Daily25Data
                     where c.Date > DbFunctions.AddYears(DateTime.Now,-1)
                     select c).ToList();
      

      【讨论】:

        猜你喜欢
        • 2011-09-30
        • 1970-01-01
        • 2017-09-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多