【发布时间】:2013-10-11 17:44:31
【问题描述】:
我目前在使用 LINQ->Entites w/Entity Framework v 4.2 和 T4 生成的对象上下文时遇到了问题。我相对了解在对数据库执行之前如何将 LINQ 查询转换为存储表达式,但我绝不是专家。据我了解,使用的 .NET 函数在 T-SQL 中被转换为它们的等效函数,而那些没有等效函数(例如,String.Format())的函数将在运行时抛出 System.NotSupportedException。
在我的动态 LINQ 查询中,我使用 DateTime.Now.AddMinutes() 过滤掉我的结果集:
public void ExecuteSearch()
{
var timeElapsedTresholdInMinutes = Convert.ToInt32( ConfigurationManager.AppSettings.Get("TimeElapsedThresholdInMinutes") );
var resultSet = ( from entity in _dbContext.EntityCollection
where /*non-date-related where clause stuff*/
&&
entity.DateAdded <= DateTime.Now.AddMinutes(-1 * timeElapsedThresholdInMinutes)
select entity);
/* do something with resultSet */
}
在运行时,我收到System.NotSupportedException: LINQ to Entities does not recognize the method DateTime.Now.AddMinutes() method and this method cannot be translated into a store expression.
例如,我的 timeElapsedThreshold 在评估后的值为 -30。有谁知道为什么这不会映射到DATEADD(MINUTE,-30,GETDATE());?我这里有什么遗漏吗?
当然,我可以把我的代码变成:
public void ExecuteSearch()
{
var maxDateTimeThreshold = DateTime.Now.AddMinutes( -1 * Convert.ToInt32(ConfigurationManager.AppSettings.Get("TimeElapsedThresholdInMinutes"));
var resultSet = ( from entity in _dbContext.EntityCollection
where /*non-date-related where clause stuff*/
&&
entity.DateAdded <= maxDateTimeThreshold
select entity);
}
并克服了我的代码破坏问题,但我真的很想了解为什么 LINQ->Entities 将 DateTime.Now.AddMinutes() 视为没有 T-SQL 等效项的 .NET 方法。非常感谢任何帮助/反馈!
【问题讨论】:
标签: c# sql linq datetime entity-framework-4