简体   繁体   中英

DateTime Conversion in Entity Framework

I'm trying to insert a datetime value to my database. I'm using entity framework with ASP.NET MVC 4 and SQL server.

using (dc = new GateEntities())
{     
   tblSite site = new tblSite();
   site.CalledInAt = DateTime.Parse("19/09/2013 00:29 AM", new CultureInfo("en- US", false));    
   dc.tblSites.Add(site);
   dc.SaveChanges();
}

When I try to save the data I get the error:

"The value '19/09/2013 00:29 AM' is not valid for CalledInAt."

I also tried Convert.ToDateTime() but no use.

This works fine in my local machine. It's not working only on my shared hosting server.

There are two errors in the code you list.

The first (which I guess is an error introduced while typing the question) is that your CultureInfo is being set to 'en- US' which should be 'en-US'

The other is that US dates are formatted Month then Day and in your string that would make the date you are setting the 19th month of the year.

This code below works for your date value...

DateTime.Parse("09/19/2013 00:29 AM", new System.Globalization.CultureInfo("en-US", false));

The exception is caused by EF's validation which happens in a culture that has a different date format than the string 19/09/2013 00:29 AM .

When it comes to assigning values to entity properties from user input, the best approach is to make sure that you are independent of UI culture. This means that in the UI (probably a view model) you have to capture user input and convert it to a DateTime value. Then you just assign the DateTime value to site.CalledInAt .

Another option is to include the UI culture in the view model and use it to do the conversion in the controller.

我在web.config中设置了区域性,它开始起作用。

 <globalization uiCulture="en" culture="en-GB" />

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.

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