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

ε祈祈猫儿з 提交于 2019-12-03 04:46:04

问题


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:


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?))


来源:https://stackoverflow.com/questions/43277154/entity-framework-core-setting-the-decimal-precision-and-scale-to-all-decimal-p

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!