2012-03-22 52 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(); 

這個重構通常是可能的,如果你想通過比較修復時間戳與其他日期時間轉移存儲的日期時間。

相關問題