LINQ to Entities不识别方法'System.DateTime ToDateTime(System.String)' [英] LINQ to Entities does not recognize the method 'System.DateTime ToDateTime(System.String)'
问题描述
_tareaRepositorio.ObtenerTodo()
.Where(
x =>
Convert.ToDateTime(x.FechaCreacion.ToString(d))> = fechaInicial&&b $ b Convert.ToDateTime(x.FechaCreacion.ToString(d) )< = fechaFinal).ToList();
但是,在执行时,查询出现以下错误:
LINQ to Entities不会识别方法'System.DateTime ToDateTime(System.String)'方法,并且此方法无法转换为存储表达式。
我可以如何解决?
编辑 / p>
麻烦的是我需要比较只是日期,而不是时间...
尝试这个
编辑:将 DbFunctions.TruncateTime()
添加到获得所需的效果
_tareaRepositorio.ObtenerTodo()
.Where(x => DbFunctions.TruncateTime(x。 FechaCreacion)> = fechaInicial&&
DbFunctions.TruncateTime(x.FechaCreacion)< = fechaFinal)
.ToList();
您获得的异常是因为 Convert.ToDateTime
是不能转换为SQL的.NET方法。通常这应该在查询实现后(即在 Where
之前)使用 .ToList()
),但在你的具体情况是不必要的,因为 DateTime
对象可以使用> =
和 ; =
和Entity Framework可以将其转换成SQL成功
现在,如果您只想比较Datetime的Date部分,可以使用方法 DbFunctions.TruncateTime()
它们位于 System.Data.Entity
命名空间内。此方法将允许EF正确截断SQL
中的日期
In LINQ I want make thw follow query:
_tareaRepositorio.ObtenerTodo()
.Where(
x =>
Convert.ToDateTime(x.FechaCreacion.ToString("d")) >= fechaInicial &&
Convert.ToDateTime(x.FechaCreacion.ToString("d")) <= fechaFinal).ToList();
But, at the moment of execute the query appears the follow mistake:
LINQ to Entities does not recognize the method 'System.DateTime ToDateTime(System.String)' method, and this method cannot be translated into a store expression.
How I can fix that ?
EDIT
The trouble is that I need compare just date, not time ...
Try this
EDIT: Add DbFunctions.TruncateTime()
to get the desired effect
_tareaRepositorio.ObtenerTodo()
.Where( x => DbFunctions.TruncateTime(x.FechaCreacion) >= fechaInicial &&
DbFunctions.TruncateTime(x.FechaCreacion) <= fechaFinal)
.ToList();
The exception you are getting is because the Convert.ToDateTime
is a .NET method that cannot be converted into SQL. Normally this should be done after the query has been materialized (i.e. using .ToList()
before the Where
) but in your particular case it is unnecesary since DateTime
objects can be compared using >=
and <=
and Entity Framework can convert it to SQL successfully
Now if you only want to compare the Date part of the Datetime you can use the method DbFunctions.TruncateTime()
which lives inside System.Data.Entity
namespace. This method will allow EF to correctly truncate the date in SQL
这篇关于LINQ to Entities不识别方法'System.DateTime ToDateTime(System.String)'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!