Search code examples
c#entity-frameworkef-code-firstentity-framework-5

Force Entity Framework 5 to use datetime2 data type


Is it possible to globally set Entity Framework DbContext to use datetime2 for all properties that are System.DateTime when using Code-First model?

I can do this for each column by using HasColumnType() method, but for an existing codebase I would like a global solution.


Solution

  • Since EF6 has been out for quite a while now and this question still shows up in searches, here is the way to use custom conventions to set the SQL type. Within OnModelCreating method in your DbContext class do:

    modelBuilder.Properties<DateTime>()
        .Configure(c => c.HasColumnType("datetime2"));