DbArithmeticExpression参数必须有一个数字常见的类型
问题描述:
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.
请帮助!
答
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
答
我知道这是一个老问题,但在特定情况下使用,而不是由DBFunctions
作为@GertArnold建议,不能你只是反转操作从Lambda中移出有问题的算术?
毕竟clientDateTime
和time24
是固定值,因此它们的差异不需要在每次迭代中重新计算。
像:
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();
这个重构通常是可能的,如果你想通过比较修复时间戳与其他日期时间转移存储的日期时间。
'clientDateTime - o.ClientDateTimeStamp'的结果是什么? – shahkalpesh 2012-03-22 10:30:37
noramlly应该是TimeSpan的一个对象,在EF异常中抛出。 – 2012-03-22 10:58:58