0

By default EF Core code first on MS SQL server generates DateTime columns as DateTime2(7). I want to change default behaviour. When no explicit precision atribute is given than Datetime2(3) should be generated, like [Precision(3)] attribute is used.

  • This behaviour (likely by intention) reflects the behaviour of SQL Server, that when you don't define a precision `datetime2(7)` is used. Why don't you want to use an explicit precision? This smells like an [XY Problem](//xyproblem.info). – Thom A Oct 17 '22 at 15:49
  • @Larnu Might be because all the dates in his system are specified to use precision 3. So he wants the default to them be 3 instead of 7 to not forget to specify it somewhere – Irwene Oct 17 '22 at 15:53
  • How about : https://stackoverflow.com/a/69922761/2245256 ? – Irwene Oct 17 '22 at 15:55
  • I wouldn't like to guess why it is what *they* need, @Irwene . Hopefully *they* will though. – Thom A Oct 17 '22 at 15:57
  • Not all dates in system, but all dates, that dosn't have explicitly set different precision. Its like 99% of datetimes and yes its because hard to track errors when Precision(3) is missing. – Milan Bačík Oct 17 '22 at 16:03

2 Answers2

1

Override this method in your DBContext.

protected override void ConfigureConventions(
ModelConfigurationBuilder configurationBuilder)
{
    configurationBuilder.Properties<DateTime>()
        .HavePrecision(3);
}

EDIT:

@MilanBačík is correct.

If you set the precision for your entities using the Fuent API in OnModelCreating it overrides the convention. But if you set the precision through data annotations it doesn't.

I believe this to be a bug in EF Core (tested on 6.0)

gcores
  • 12,376
  • 2
  • 49
  • 45
  • That work, but set precision 3 to all datetimes. I want to set it only to ones without explicit Precision attribute. – Milan Bačík Oct 17 '22 at 16:16
  • @MilanBačík As far as I understand it setting the precision explicitly will override the convention. – gcores Oct 17 '22 at 16:21
  • tryed this and still not work - all instancies has precision 3 var props=configurationBuilder.Properties(); props.HavePrecision(props.GetType().GetCustomAttribute()?.Precision ?? 3); – Milan Bačík Oct 18 '22 at 12:11
1

I have found a working solution. I have to use OnModelCreating

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    foreach (var entityType in modelBuilder.Model.GetEntityTypes())
    {
        foreach (var property in entityType.GetProperties())
        {
            if (property.ClrType == typeof(DateTime) || property.ClrType == typeof(DateTime?))
            {
                if (property.GetPrecision() == null)
                {
                    property.SetPrecision(3);
                }
            }
        }
    }
}