How to switch to datetime2 in Entity Framework / SQL Server 2008 project

mykola picture mykola · Mar 28, 2013 · Viewed 15k times · Source

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?

Answer

Mark Shapiro picture Mark Shapiro · Dec 11, 2015

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.