加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – LINQ to Entities无法识别方法’System.DateTime ToDateTi

发布时间:2020-12-15 08:46:53 所属栏目:百科 来源:网络整理
导读:在LINQ中我想要跟随查询: _tareaRepositorio.ObtenerTodo() .Where( x = Convert.ToDateTime(x.FechaCreacion.ToString("d")) = fechaInicial Convert.ToDateTime(x.FechaCreacion.ToString("d")) = fechaFinal).ToList(); 但是,在执行时,查询出现以下错误
在LINQ中我想要跟随查询:
_tareaRepositorio.ObtenerTodo()
  .Where(
   x =>
     Convert.ToDateTime(x.FechaCreacion.ToString("d")) >= fechaInicial &&
     Convert.ToDateTime(x.FechaCreacion.ToString("d")) <= fechaFinal).ToList();

但是,在执行时,查询出现以下错误:

LINQ to Entities does not recognize the method ‘System.DateTime ToDateTime(System.String)’ method,and this method cannot be translated into a store expression.

我怎么解决这个问题?

编辑

麻烦的是我需要比较日期,而不是时间……

解决方法

试试这个

编辑:添加DbFunctions.TruncateTime()以获得所需的效果

_tareaRepositorio.ObtenerTodo()
    .Where( x => DbFunctions.TruncateTime(x.FechaCreacion) >= fechaInicial &&
                 DbFunctions.TruncateTime(x.FechaCreacion) <= fechaFinal)
    .ToList();

您获得的异常是因为Convert.ToDateTime是一个无法转换为SQL的.NET方法.通常这应该在查询实现之后完成(即在Where之前使用.ToList())但在特定情况下它是不必要的,因为可以使用> =和< =来比较DateTime对象,并且实体框架可以转换它到SQL成功 现在,如果您只想比较Datetime的Date部分,可以使用位于System.Data.Entity命名空间内的方法DbFunctions.TruncateTime().此方法将允许EF在SQL中正确截断日期

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读