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


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

  • 相关阅读:
    工作中简单又实用的vim配置
    宏定义的专业写法(工作中常用)
    17八皇后问题
    04文件与IO
    响应式布局编码
    静态布局,自适应布局,流体式布局,响应式布局概念
    CSS:<link>标签rel和media的解释
    我想去的公司的入职要求
    JS:引用类型,基本类型
    Android Launcher 详解
  • 原文地址:https://www.cnblogs.com/cw_volcano/p/3241351.html
Copyright © 2020-2023  润新知