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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
mykola
  • 1,598
  • 2
  • 12
  • 15
  • Possible duplicate of [Force Entity Framework 5 to use datetime2 data type](https://stackoverflow.com/questions/15248488/force-entity-framework-5-to-use-datetime2-data-type) – hazzik Sep 21 '17 at 04:04

2 Answers2

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.

Mark Shapiro
  • 1,192
  • 10
  • 13
  • 1
    IIRC this is EF6 only. – Der Kommissar Jan 10 '17 at 07: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. – Mark Shapiro Jan 11 '17 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

Community
  • 1
  • 1
Floremin
  • 3,969
  • 15
  • 20
  • 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 '13 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 '13 at 06:48