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).
Todays records:
return View(db.Things
.Where(t => t.DateTimeObj.Date == DateTime.Today)
.OrderByDescending(e => e.DateTimeObj)
.Take(num)
);
Last 24 hours records:
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:
- SQL Server only (probably?)
- Date computations are held off to be performed by SQL Server, as oposed to supplying a pre computed date in the linq2sql translation.
Take a look at the SqlFunctions class on msdn which provides access to the sql datediff etc functions.
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. Obviously this is SQL Server only unless other providers have wrapped these functions.
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)
);
精彩评论