1

I'm trying to create a linq query to get all date 1 year back (expecting 365 values)

 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);
 }

tried to use the above code but get exception

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.

2 Answers 2

4

You can just pull the value out into a variable before you execute your query:

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

var query = (from c in context.Daily25Data
             where c.Date > oneYearEarlier
             select c).ToList();
Sign up to request clarification or add additional context in comments.

Comments

2

Agreed with the @RB answer. You can also use DbFunctions.AddYears static method:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.