c# - LINQ to Entities - 比较日期

标签 c# linq datetime date linq-to-entities

是否有更好(更好/更有效)的方法来做到这一点?

return View(db.Things
    .Where(t => t.DateTimeObj.Month == DateTime.Today.Month 
        && t.DateTimeObj.Day == DateTime.Today.Day)
    .OrderByDescending(e => e.DateTimeObj)
    .Take(num)
);

以下不起作用(LINQ to Entites 中没有 Date 对象)。

今日记录:

return View(db.Things
    .Where(t => t.DateTimeObj.Date == DateTime.Today)
    .OrderByDescending(e => e.DateTimeObj)
    .Take(num)
);

最近24小时记录:

return View(db.Things
    .Where(t => t.DateTimeObj > DateTime.Today.AddHours(-24))
    .OrderByDescending(e => e.DateTimeObj)
    .Take(num)
);

编辑:

这似乎可以解决问题:

return View(db.Things
    .Where(t => t.DateTimeObj > SqlFunctions.DateAdd("dd", -1, DateTime.Now))
    .OrderByDescending(e => e.DateTimeObj)
    .Take(num)
);

Chris Sainty 指出的可能陷阱:

  1. 仅限 SQL Server(可能?)
  2. 日期计算推迟由 SQL Server 执行,而不是在 linq2sql 转换中提供预先计算的日期。

最佳答案

查看 msdn 上的 SqlFunctions 类它提供对 sql datediff 等函数的访问。

请注意,它们不能用于在 C# 中运行代码,它们只是占位符,查询解析器可以理解并可以将其转换为 T-SQL。显然,这仅适用于 SQL Server,除非其他供应商已经包装了这些功能。

关于c# - LINQ to Entities - 比较日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6435927/

相关文章:

c# - 如何处理冲突的编码约定?

datetime - 使用 PowerShell 将月份数字转换为月份名称

c# 使用 this.Invoke 安全吗?

c# - ConditionalWeakTable 的值会导致内存泄漏吗?

c# - C#条件OrderBy

c# - 选择 LINQ 中不存在子行的行

c# - 使用 Entity Framework 的 Oracle 查询速度慢得离谱

excel - 将日期从 Excel 文件转换为 pandas

javascript-如何使用 moment.js(或替代库)解析日期以选出 2 月 31 日或 6 月 31 日等。无效?

c# - 使用VS2019创建WebService