c# - LINQ to Entities 无法识别方法 'System.DateTime ToDateTime(System.String)'

标签 c# linq entity-framework

在 LINQ 中,我想让 thw 跟随查询:

_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 方法。通常这应该在查询实现后完成(即在 .ToList() 之前使用 Where )但在您的特定情况下,这是不必要的,因为 DateTime可以使用 >= 比较对象和 <= Entity Framework可以成功将其转换为SQL

现在,如果您只想比较日期时间的日期部分,您可以使用方法 DbFunctions.TruncateTime()住在里面System.Data.Entity命名空间。此方法将允许 EF 正确截断 SQL 中的日期

关于c# - LINQ to Entities 无法识别方法 'System.DateTime ToDateTime(System.String)',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30240879/

相关文章:

c# - C#的财务图表组件

c# - 如果找不到我输入的记录,如何在 SQL 中找到下一个更大的可用记录

c# - Migrate.Exe Entity Framework 空异常错误

c# - 使用Linq判断记录是否存在于列表中但存在于表中

c# - int' 不包含 'contains' 的定义,并且找不到接受类型为 'contains' 的第一个参数的扩展方法 'int'

c# - 为什么 GC System.Threading.OverlappedData 需要这么长时间?

c# - 使用 Javascript 时 C# 中的命名空间

c# - 在客户端运行时更新 Silverlight 应用程序

c# - 有没有办法将不同的 keySelector 返回给一个 OrderBy?

c# 获取在列表中的某个元素之间分组的新元素列表