• LINQ to Entities does not recognize the method , and this method cannot be translated into a store expression 解决办法


    根据用户输入的起始日期,查询以起始日期开始的前20条记录,在ASP.NET MVC的Controller代码中这样写:

                var Logs = db.Log.Take(20);
           if (!string.IsNullOrEmpty(dateBegin)) { Logs = Logs.Where(a => a.Date >= Convert.ToDateTime(dateBegin)).Take(20); }

    运行后,出现下面错误信息:

    对于这种情况,要清楚:本表达式只是LINQ to Entities,而不是真正的C#语言,虽然上述代码在编译是没有错误,但运行时,转换为SQL就产生了错误,无法转换为存储表达式。

    解决办法是:将用户输入的起始日期的转换提前一步,使用真正的C#代码完成,然后将转换后的变量代入到LINQ表达式内,修改后的代码可以这样:

                var Logs = db.Log.Take(20);
           if (!string.IsNullOrEmpty(dateBegin)) { DateTime dateB = Convert.ToDateTime(dateBegin); Logs = Logs.Where(a => a.Date >= dateB).Take(20); }

    可以看到,首先将转换后的日期存入变量dateB内,然后再使用LINQ调用,不在LINQ中直接使用方法。

    运行,正常。不再出现错误信息。


     

  • 相关阅读:
    类 2020年8月19
    随便一写,明天改正
    os模块 2020年8月16
    time 模块 2020年8月16
    collections模块 2020年8月16
    正则跟re模块内容2020年8月16日
    【C++设计模式二】C++工厂模式
    【C++设计模式一】C++简单工厂模式
    【01-springmvc快速入门、组件解析】
    03-【Spring 的 AOP】
  • 原文地址:https://www.cnblogs.com/wusir/p/3477435.html
Copyright © 2020-2023  润新知