Cloud Training (Online)




Not supported in LINQ to Entities and Entity Framework ..

I was forced to explore something interesting when i was playing around with the Entity Framework and executing the below LINQ query.

EmployeeEntities entityContext = new EmployeeEntities();
var Records = (from m in entityContext.Employees
  Select m).LastOrDefault();

My assumption was that the result would be the last record in the table .. But to my surprise , it threw an Exception

LINQ to Entities does not recognize the method ‘Employees’ Last(System.Linq.IQueryable`1[Employees])’ method, and this method cannot be translated into a store expression.

Instead , the below query worked..


EmployeeEntities entityContext = new EmployeeEntities();
var Records = (from m in entityContext.Employees
  Select m).List<Employees>().LastOrDefault();

Interestingly , here’s the reason why i got the error .

The above said functions and there are still quite a few LINQ operators that are not supported in the LINQ to Entities and the reason why other query worked with List is simply because the data from the SQL is loaded to the Generic List first and the LastOrDefault is applied directly to the List and not to the SQL .

You can find the list of functions that are not supported in .NET Framework in the MSDN site

Supported and Unsupported LINQ Methods (LINQ to Entities)

Moral of the story is “Get to know what is supported and not supported , before we start”.:)