Entity Framework Core - setting decimal precision and scaling for all decimal values

I want to set the accuracy of all decimal properties (18.6). In EF6, this was pretty simple:

modelBuilder.Properties<decimal>().Configure(x => x.HasPrecision(18, 6));

but I cannot find anything like this in EF Core. Removing the cascade exception convention was not as easy as in EF6, so I found the following workaround:

EF6:

modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();

EF Core:

foreach (var relationship in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
    relationship.DeleteBehavior = DeleteBehavior.Restrict;

and after I read this one , I tried a similar approach:

foreach (var entityType in modelBuilder.Model.GetEntityTypes()
    .SelectMany(x => x.GetProperties())
    .Where(x => x.ClrType == typeof(decimal)))
        {
            // what to do here?
        }

I would like if I were on the right track and how to proceed, or if not, I should start putting data annotations in all properties decimal.

+29
source share
1

. .

foreach (var property in modelBuilder.Model.GetEntityTypes()
    .SelectMany(t => t.GetProperties())
    .Where(p => p.ClrType == typeof(decimal)))
{
    // EF Core 1 & 2
    property.Relational().ColumnType = "decimal(18, 6)";

    // EF Core 3
    //property.SetColumnType("decimal(18, 6)");
}

: decimal?, :

Where(p => p.ClrType == typeof(decimal) || p.ClrType == typeof(decimal?))
+56

Source: https://habr.com/ru/post/1016385/


All Articles