Reputation: 676
I am trying to return a view which will display the logs from current day.
This sql query does exactly what i need:
select * from Logs where Date>=GETDATE()-1
but I am having trouble with the razor syntax to write this statement in my view.
return View(db.Logs.Where(a => a.Date >= DateTime.Today()-1));
Any idea how to display logs in the view for the current date?
Upvotes: 1
Views: 2343
Reputation: 8166
If you're trying to get logs from the current day, do you mean from midnight of the current day until now, or the past 24 hours.
Your original query in SQL using GETDATE()
is equivelent to DateTime.Now
, not DateTime.Today
As Serv has mentioned, what exactly is the results that you're getting that are incorrect? My suggestions for duplicating what you're seeing from your sql query would be this:
return View(db.Logs.Where(a => a.Date >= DateTime.Now.AddDays(-1)));
If you want it to display for the current date since midnight, use this:
return View(db.Logs.Where(a => a.Date >= DateTime.Today));
But might I also make an additional suggestion, do not return your entity objects directly to the view, map them over to a view model object and send that to your view with ONLY the data that you need from your entity (even if it includes all the fields)
Upvotes: 1
Reputation: 23937
It is either:
return View(db.Logs.Where(a => a.Date == DateTime.Today));
or, if you want to substract one day:
return View(db.Logs.Where(a => a.Date >= DateTime.Today.AddDays(-1)));
Please note, that DateTime is a struct and Now
, Today
or Date
are properties, not methods, so you can not call them like method (DateTime.Today()
).
They are called just like any other property, without the paranthesis.
Reference: http://msdn.microsoft.com/en-us/library/system.datetime.aspx
Off-Topic:
I have tried this one but it doesn't work.
Is a bad phrasing here on SO. People tend to react allergic to this, as it does not state, what excatly is wrong. Do you get unexpected results, exceptions, compiler-warnings etc. In your case it was fairly simple, because you were dealing with some syntactic mistakes, but in a more complex scenario, this will not go well.
Upvotes: 3