Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to get Linq-to-entities to evaluate a local expression

Lets say you have the following linq expression:

from o in salesEntities.Orders where o.OrderDate < DateTime.Today.AddDays(-20) select o

Entity Framework does not know how to translate DateTime.Today.AddDays(-20) into an Entity SQL expression, and you get the following error:

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

So here is my questions: Is there any way to get Linq to Entities to evaluate part of the lambda expression and substitute a constant value, without me having to declare a local variable to hold it?

like image 331
Darren Avatar asked Dec 03 '22 09:12

Darren


2 Answers

LINQ-to-Entities can deal with local values but not local expressions. Your code will work with this minor change:

var pastDate = DateTime.Today.AddDays(-20);

from o in salesEntities.Orders where o.OrderDate < pastDate select o

like image 70
Robert Levy Avatar answered Dec 24 '22 15:12

Robert Levy


Change your expression using the EntityFunction for add days like this:

var result =
(
from o in salesEntities.Orders 
where o.OrderDate < System.Data.Objects.EntityFunctions.AddDays(DateTime.Today,-20) 
select o
);
like image 31
Hallgeir Engen Avatar answered Dec 24 '22 13:12

Hallgeir Engen