在 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/