c# - 如何仅比较 LINQ to Entities 中 TimeSpan 的分钟部分?

标签 c# sql linq entity-framework time

我的模型中有一个 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/

相关文章:

javascript - 如何使用 angularjs 获取用户所属的安全组列表

c# - Runspace Powershell 命令的 WSManConnectionInfo 和 PSCredential 作为另一个用户

sql - 如何将表从一个数据库移动到另一个数据库

php - 如何获取 mysql 日期时间字段作为 php 中的日期时间?

mysql - 如何从结果查询中排除第一行?

.net - linq 查询中的 String.Format

c# - 集成测试中的 MVC 策略覆盖

c# - Monitor.Pulse 和 Monitor.Wait 有什么优势?

.net - 构建 'flat'而不是 'tree' LINQ表达式

c# - 先按大写字母排序