DbArithmeticExpression参数必须具有数字公共类型

Naw*_*.io 114 c# ado.net entity-framework

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(); 
Run Code Online (Sandbox Code Playgroud)

此Linq表达式抛出此异常:

DbArithmeticExpression arguments must have a numeric common type.
Run Code Online (Sandbox Code Playgroud)

请帮忙!

Ger*_*old 233

DateTime实体框架6及更早版本不支持算术.你必须使用DbFunctions*.因此,对于陈述的第一部分,例如:

var sleeps = context.Sleeps(o =>
    DbFunctions.DiffHours(o.ClientDateTimeStamp, clientDateTime) < 24);
Run Code Online (Sandbox Code Playgroud)

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

Entity Framwork核心(当与Sql Server一起使用时,可能是其他数据库提供程序)支持DateTime AddXxx函数(如AddHours).它们被翻译成DATEADDSQL.

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