2012-03-22 75 views
91
TimeSpan time24 = new TimeSpan(24, 0, 0); 
TimeSpan time18 = new TimeSpan(18, 0, 0);  

// first get today's sleeping hours 
List<Model.Sleep> sleeps = context.Sleeps.Where(
    o => (clientDateTime - o.ClientDateTimeStamp < time24) && 
      o.ClientDateTimeStamp.TimeOfDay > time18 && 
      clientDateTime.TimeOfDay < time18 && 
      o.UserID == userid).ToList(); 

这LINQ表达式抛出此异常:DbArithmeticExpression参数必须有一个数字常见的类型

DbArithmeticExpression arguments must have a numeric common type. 

请帮助!

+0

'clientDateTime - o.ClientDateTimeStamp'的结果是什么? – shahkalpesh 2012-03-22 10:30:37

+0

noramlly应该是TimeSpan的一个对象,在EF异常中抛出。 – 2012-03-22 10:58:58

回答

189

Entity Framework 6及更早版本不支持DateTime的算术运算。你必须使用DbFunctions *。因此,对于您语句的第一部分,是这样的:

var sleeps = context.Sleeps(o => 
    DbFunctions.DiffHours(o.ClientDateTimeStamp, clientDateTime) < 24); 

注意,DiffHours方法接受Nullable<DateTime>

实体Framwork芯(与SQL Server,也许其它分贝提供商使用时)支持的DateTime AddXxx函数(如AddHours)。它们在SQL中被翻译为DATEADD

* EntityFunctions之前的实体框架版本6

1

我知道这是一个老问题,但在特定情况下使用,而不是由DBFunctions作为@GertArnold建议,不能你只是反转操作从Lambda中移出有问题的算术?

毕竟clientDateTimetime24是固定值,因此它们的差异不需要在每次迭代中重新计算。

像:

TimeSpan time24 = new TimeSpan(24, 0, 0); 
TimeSpan time18 = new TimeSpan(18, 0, 0);  

var clientdtminus24 = clientDateTime - time24; 

// first get today's sleeping hours 
List<Model.Sleep> sleeps = context.Sleeps.Where(
    o => (clientdtminus24 < o.ClientDateTimeStamp) && 
      o.ClientDateTimeStamp.TimeOfDay > time18 && 
      clientDateTime.TimeOfDay < time18 && 
      o.UserID == userid).ToList(); 

这个重构通常是可能的,如果你想通过比较修复时间戳与其他日期时间转移存储的日期时间。

相关问题