Entity Framework Core - setting the decimal precision and scale to all decimal properties

asp.net-core c# entity-framework entity-framework-core

Question

I want to set the precision of all the decimal properties to (18,6). In EF6 this was quite easy:

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

but I can't seem to find anything similar to this in EF Core. Removing the cascade delete convention wasn't as simple 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, 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 am on the right track and how to continue, or if not, should I start putting data annotations on all the decimal properties.

1
38
5/23/2017 12:25:53 PM

Accepted Answer

You got close. Here's the code.

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)");
}

Note: if you have nullable types as decimal?, use:

Where(p => p.ClrType == typeof(decimal) || p.ClrType == typeof(decimal?))
82
10/17/2019 5:57:41 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