我的模型中有一个 Publication 实体。我想检索从现在起不到 10 分钟创建的所有出版物。
var publications = myEntities.Publications.
.Where(p => p.CreationUserId == exampleId
&& (DateTime.Now - p.CreationDate).Minutes < 10);
尝试执行上述语句时,出现以下异常:“DbArithmeticExpression 参数必须具有数字通用类型。”。我试图从 DbFunctions 类中寻找合适的函数,但没有成功。有人能想出解决办法吗?
最佳答案
不要在查询中进行算术运算 - 在查询之前进行运算,这样您基本上就是在指定“最早的发布创建时间”:
// Deliberate use of UtcNow - you should almost certainly be storing UTC, not
// local time...
var cutoff = DateTime.UtcNow.AddMinutes(-10);
var publications = myEntities.Publications
.Where(p => p.CreationUserId == exampleId &&
p.CreationDate >= cutoff);
请注意,即使您的原始查询确实 有效,它也不会执行您想要的操作 - 它会返回 0-10 分钟前、60-70 分钟前、120-130 分钟前创建的出版物等等。你想要 TotalMinutes
而不是。
关于c# - 如何仅比较 LINQ to Entities 中 TimeSpan 的分钟部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25365572/