EF Core Conventions for datetime2

entity-framework-core

Question

I've worked on an EF 6 project where in framework code we had a Convention defined to ensure that all entity POCOs that had a C# DateTime would map to datetime2 in Sql Server. Now that there's no Conventions how could I achieve this in EF Core?

1
0
3/25/2019 10:39:20 PM

Accepted Answer

Thanks @DavidG. Based on the link you sent I think this will work (I'm on a corporate network right now with a group policy that's not allowing NuGet Package Manager Console to invoke the init.ps1 for entityframeworkcore.tools so I'll have to wait to try this at home)

foreach (var entity in modelBuilder.Model.GetEntityTypes())
{
    var dateTimeProps = entity.GetProperties()
        .Where(p => p.PropertyInfo.PropertyType == typeof(DateTime));
    foreach (var prop in dateTimeProps)
    {
        modelBuilder.Entity(entity.Name).Property(prop.Name).HasColumnType("datetime2");
    }

}
1
5/16/2019 9:55:57 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow