I am trying to create a strongly-typed model and view. This portion of code is supposed to return a list of "emails" sent in a contact-us form.
I want to return all form submissions sent today. The SQL Server 2008 datatype is datetime
. So I have a DateTime
field in my model.
public ActionResult ResultTable()
{
CombinedReport report = new CombinedReport();
report.emails = report.db.ContactEmails.Where(w => w.FormInserted.Equals(DateTime.Today)).ToList();
return PartialView(report);
}
When I ran this configured for the local built-in SQL Server CE, it worked fine.
When I set it up for our actual database running SQL Server 2008, it doesn't work.
With some trial-and-error, and looking at code in other parts of my program, I noticed that the C# implementation of DateTime
is including 12:00:00AM
as a part of the date, and when it's doing the comparison to SQL, it's sending that exact time in.
It won't let me compare a DateTime
to a string, so I can't even format "today" as a string.
The CombinedReport model I instantiate here is just a view model for a specific page and doesn't directly map to a database ("ContactEmails" does).
What is the best way to go forward that will let me keep a strongly-type view and model?
If you only want to compare the date part of the value, you should make that explicit:
DateTime today = DateTime.Today;
report.emails = report.db.ContactEmails
.Where(w => w.FormInserted.Date == today)
.ToList();
Now whether the flavour of LINQ you're using supports the Date
property is a different matter - but that's what I'd try to start with.
如果您使用的是EF,请使用EntityFunctions.TruncateTime
方法:
.Where(w => EntityFunctions.TruncateTime(w.FormInserted).Equals(DateTime.Today))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.