0

I have a method that looks like this

public class Site
{
    public virtual ICollection<SalesOrder> soDetails { get; private set; }

    public int? IncomingOSI(Site s)
    {
        PIC_Program_1_0Context db = new PIC_Program_1_0Context();
        List<SalesOrder> so = db.SalesOrders
          .Where(x => x.siteID == s.ID)
          .Where(x => x.DateCreated > DateTime.Now.AddDays(-30)).ToList();
    }
}

But currently this returns an error of

'LINQ to Entities does not recognize the method 'System.DateTime AddDays(Double)' method, and this method cannot be translated into a store expression.'

What is the reason for this?

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
chris
  • 121
  • 11
  • Side note: you likely searched for error message https://www.bing.com/search?q=LINQ+to+Entities+does+not+recognize+the+method+'System.DateTime+AddDays but for some reason decided not to show results of your research in the post. That may lead to post being downvoted due to "this question does not show any research effort"... – Alexei Levenkov Mar 25 '20 at 17:08
  • @AlexeiLevenkov Okay thanks for clarifying – chris Mar 25 '20 at 17:20

1 Answers1

1

Declare it as a variable outside of the linq expression.

public class Site
{
   public virtual ICollection<SalesOrder> soDetails { get; private set; }

   public int? IncomingOSI(Site s)
   {
      PIC_Program_1_0Context db = new PIC_Program_1_0Context();

      // declare it outside of the expression
      var less30days = DateTime.Now.AddDays(-30);

      List<SalesOrder> so = db.SalesOrders.Where(x => x.siteID == s.ID).Where(x => x.DateCreated > less30days).ToList();
   }
}

The answer here explains why; Linq won't be able to run other C# code as it will have issues turning it to a sql expression.

LINQ to Entities does not recognize the method

Jerdine Sabio
  • 5,688
  • 2
  • 11
  • 23
  • Could you not combine those two `Where()` conditions into one: `Where(x => x.siteID == s.ID && x => x.DateCreated > less30days)`? – RoadRunner Mar 25 '20 at 17:08