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

时间:2023-12-22 12:38:38

根据用户输入的起始日期,查询以起始日期开始的前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();
}

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

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

对于这种情况,要清楚:本表达式只是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();
}

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

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