比较 Linq 中的 DateTime 对象

Comparing DateTime object in Linq

我正在尝试创建一个 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);
 }

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

Additional information: LINQ to Entities does not recognize the method 'System.DateTime AddYears(Int32)' method, and this method cannot be translated into a store expression.

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

var oneYearEarlier = DateTime.Now.AddYears(-1);

var query = (from c in context.Daily25Data
             where c.Date > oneYearEarlier
             select c).ToList();

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

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