简体   繁体   English

将DateTime与ASP.NET MVC和SQL Server进行比较

[英]Comparing DateTime with ASP.NET MVC and SQL Server

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 . SQL Server 2008数据类型是datetime So I have a DateTime field in my model. 所以我的模型中有一个DateTime字段。

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. 当我为本地内置的SQL Server CE配置运行时,它工作正常。

When I set it up for our actual database running SQL Server 2008, it doesn't work. 当我为运行SQL Server 2008的实际数据库设置它时,它不起作用。

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. 通过一些反复试验,并查看程序其他部分的代码,我注意到DateTime的C#实现包括作为日期的一部分的12:00:00AM ,当它与SQL进行比较时,它正在发送确切的时间。

It won't let me compare a DateTime to a string, so I can't even format "today" as a string. 它不会让我将DateTime与字符串进行比较,因此我甚至无法将“今天”格式化为字符串。

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). 我在这里实例化的CombinedReport模型只是特定页面的视图模型,并不直接映射到数据库(“ContactEmails”确实)。

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. 现在,您使用的LINQ的味道是否支持Date属性是另一回事 - 但这就是我试图开始的。

如果您使用的是EF,请使用EntityFunctions.TruncateTime方法:

.Where(w => EntityFunctions.TruncateTime(w.FormInserted).Equals(DateTime.Today))

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

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