实体框架核心 - 将小数精度和比例设置为所有小数属性

时间:2017-04-07 11:37:16

标签: c# entity-framework asp.net-core entity-framework-core

我想将所有小数属性的精度设置为(18,6)。在EF6中,这非常简单:

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

但我似乎无法在EF Core中找到类似的内容。删除级联删除约定并不像在EF6中那样简单,因此我找到了以下解决方法:

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;

在我阅读this之后,我尝试了类似的方法:

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

我想如果我走在正确的轨道上以及如何继续,或者如果没有,我是否应该开始在所有decimal属性上添加数据注释。

1 个答案:

答案 0 :(得分:45)

你很亲密。这是代码。

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

注意:如果您的可归类型为decimal?,请使用:

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