简体   繁体   English

LINQ to Entities - 比较日期

[英]LINQ to Entities - Comparing Dates

Is there a better (nicer/more efficient) way to do this? 是否有更好(更好/更有效)的方法来做到这一点?

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

The following do not work (no Date object in LINQ to Entites). 以下不起作用(LINQ to Entites中没有Date对象)。

Todays records: 今日记录:

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

Last 24 hours records: 过去24小时记录:

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

Edit: 编辑:

This seems to do the trick: 这似乎可以解决问题:

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

Possible gotchas as pointed out by Chris Sainty: Chris Sainty指出的可能的陷阱:

  1. SQL Server only (probably?) 仅限SQL Server(可能?)
  2. Date computations are held off to be performed by SQL Server, as oposed to supplying a pre computed date in the linq2sql translation. 日期计算由SQL Server执行,因为选择在linq2sql转换中提供预先计算的日期。

Take a look at the SqlFunctions class on msdn which provides access to the sql datediff etc functions. 看一下msdn上的SqlFunctions类,它提供了对sql datediff等函数的访问。

Note they can not be used to run the code in C# they are just placeholders that the query parser understands and can convert to T-SQL. 请注意,它们不能用于在C#中运行代码,它们只是查询解析器理解并可以转换为T-SQL的占位符。 Obviously this is SQL Server only unless other providers have wrapped these functions. 显然这只是SQL Server,除非其他提供程序包装了这些函数。

Simply declare your 'compare to' dates before hand 只需在此之前声明您的“比较”日期

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

//Last 24 hours records:
var yesterday = DateTime.Now.AddDays(-1);
return View(db.Things
    .Where(t => t.DateTimeObj > yesterday)
    .OrderByDescending(e => e.DateTimeObj)
    .Take(num)
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM