We have an Entity Framework 5.0 project with code-first migrations with SQL Server 2008 but all date properties were created in the database as datetime
columns - not datetime2
.
Is it possible to create migration using add-migration that will update all datetime
columns in the database? Is there any other easy way to switch to datetime2
everywhere?
Always use the format YYYY-MM-DD hh:mm:ss[. nnnnnnn] to insert the date into database. This is the default format that SQL Server uses. It is also the safe format and can be interpreted only in one way.
The main difference is the way of data storage: while in Datetime type, the date comes first and then time, in Datetime2, 3 bytes, in the end, represents date part!
cshtml page is using @Html. EditorFor . Then the attribute needs to be DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyInEditMode=true)] . Note the format string - it will generate the browsers implementation of a datepicker and display it in the culture of the browser.
Defines a date that is combined with a time of day that is based on 24-hour clock. datetime2 can be considered as an extension of the existing datetime type that has a larger date range, a larger default fractional precision, and optional user-specified precision.
This is an old post, but if you want to switch ALL your datetime columns to datetime2, and use datetime2 for any new columns you add (in other words, make EF use datetime2 by default), you can add this to the OnModelCreating method on your context:
modelBuilder.Properties<DateTime>().Configure(c => c.HasColumnType("datetime2"));
That will get all the DateTime and DateTime? properties on all the entities in your model.
You can use fluent API to force creating datetime2
columns in DB.
I found this:
Using DateTime properties in Code-First Entity Framework and SQL Server
You should be able to get the idea.
Or, if you have to stick with the existing DB then you should be able to create a migration that executes custom T-SQL code. There is an example here:
http://msdn.microsoft.com/en-us/data/jj591621.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With