关于.ToList(): LINQ to Entities does not recognize the method ‘xxx’ method, and this method cannot be translated into a store expression.

时间:2022-05-16 07:01:33

LINQ to Entities works by translating LINQ queries to SQL queries, then executing the resulting query on the database and converting the result back to application entities. Because of this crossover of two languages, it will only work when SQL-compatble method calls are made. When an incompatible call is made, it’ll throw an exception along the lines of:

LINQ to Entities does not recognize the method 'xxx' method, and this method cannot be translated into a store expression.

For example the following code will throw this exception:

var result = db.Users.Select(p => new { BirthYear = Convert.ToInt16(p.Year) }).ToList();

Because SQL doesn’t have the .NET based System.Convert class, it can’t translate this call to SQL and hence raises the exception. The way around this is to retrieve the data first, then do any .NET transforms or function calls after:

var result = db.Users.ToList().Select(p => new { BirthYear = Convert.ToInt16(p.Year) }).ToList();

The only difference is that ToList() (or any other method that will execute an IQueryable) is called first that brings the Users data into .NET memory, with the subsequent Convert option done aftewards.

“DataContext accessed after Dispose” error:解决方法,在最后加上.ToList()