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 s开发者_如何学编程tore 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?
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
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
);
The short answer is no. Everything in a linq to entities expression must be either in a local variable or able to be translated into a sql expression by the entity framework.
精彩评论