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

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()

转载于:https://www.cnblogs.com/cw_volcano/p/3241351.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值