20

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?

1

2 Answers 2

49

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.

2
  • 1
    IIRC this is EF6 only. Jan 10, 2017 at 7:44
  • Yes, this is EF6 only, though it may also work on EF5 (if you're using EF5, upgrade to 6!) EF7 / EF Core have significantly different implementation from EF6, and I don't recall if EF4 / EF5 supported this or not. Jan 11, 2017 at 19:20
10

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

2
  • thanks Floremin. I can indeed create migration with custom SQL. Is there any way to automate the switch? Is there any way to tell code-first to use datetime2 for any new Date property in the future?
    – mykola
    Mar 29, 2013 at 11:02
  • I think the first link explains exactly that. Fluent API is the way to customize default code-first behaviour.
    – Floremin
    Mar 31, 2013 at 6:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.