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”.:)

Senthil Kumar B
Senthil Kumar is a former Microsoft MVP (Most Valuable Professional). He is a Co-Author of the book "Windows 10 Development Recipes using JavaScript and CSS" for Apress Publication. He is a technical presenter, blogger, mentor and a Geek.  Senthil is a regular speaker is various local user groups. He has presented at conferences like Great Indian Developer Summit (GIDS) & Microsoft DevCamps. You can reach out to him via his Twitter handle @isenthil.