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.
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"));
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With