Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 280
Knaģis Avatar asked Mar 06 '13 13:03

Knaģis


2 Answers

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")); 
like image 99
Søren Boisen Avatar answered Oct 03 '22 12:10

Søren Boisen


Not in EF5 but EF6 (currently in alpha version) allow this with custom conventions. For EF5 you would need some custom convention based framework based on reflection which would add HasColumnType calls to model builder through reflection - check for example EF Code First Extras (it claims to have support for pluggable conventions).

like image 23
Ladislav Mrnka Avatar answered Oct 03 '22 12:10

Ladislav Mrnka