动态LINQ查询中的DateTime.AddMinutes()问题

Eri*_*cup 3 c# sql linq datetime entity-framework-4

我目前正在使用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 */
}
Run Code Online (Sandbox Code Playgroud)

在运行时,我得到了 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);
}
Run Code Online (Sandbox Code Playgroud)

并且克服了我的代码破解问题,但我真的很想理解为什么LINQ-> Entities认为它DateTime.Now.AddMinutes()是一个没有T-SQL等价的.NET方法.任何帮助/反馈都非常感谢!

Hab*_*bib 11

LINQ表达式转换为下层数据源语言,在您的情况下,它SQL在LINQ to Entities DateTime.AddMinutes中没有任何实现可以将查询转换为SQL中的相应等效项.这就是.Net框架提供的原因.

System.Data.Objects.EntityFunctions.AddMinutes
Run Code Online (Sandbox Code Playgroud)

您应该看到:日期和时间规范函数

您可以将查询视为:

   var resultSet = ( from entity in _dbContext.EntityCollection
                     where /*non-date-related where clause stuff*/
                           && 
                           entity.DateAdded <= 
                          System.Data.Objects.EntityFunctions.AddMinutes(
                                 DateTime.Now, -1 * timeElapsedThresholdInMinutes)
                     select entity);
Run Code Online (Sandbox Code Playgroud)

但是在你的情况下,如果你可以像在第二个代码示例中那样预先计算值,那么它会更好,因为这将避免每个记录的转换.

  • 这已移至`System.Data.Entity.DbFunctions`.`[已过时("此类已被System.Data.Entity.DbFunctions取代.")]` (5认同)

Unr*_*ess 5

EntityFunctions已过时(EF 6.x)。

请使用DbFunctions类进行DateTime操作。

例如从上下文中的cmd。命令,其中cmd.ExecutedOn> DbFunctions.AddMilliseconds(baseDate,millisecondsToAdd)选择cmd