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

Gre*_*eMD 31 c# entity-framework entity-framework-core asp.net-core

我想将所有十进制属性的精度设置为(18,6).在EF6中,这非常简单:

modelBuilder.Properties<decimal>().Configure(x => x.HasPrecision(18, 6));
Run Code Online (Sandbox Code Playgroud)

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

EF6:

modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
Run Code Online (Sandbox Code Playgroud)

EF核心:

foreach (var relationship in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
    relationship.DeleteBehavior = DeleteBehavior.Restrict;
Run Code Online (Sandbox Code Playgroud)

我看后这个,我尝试了类似的方法:

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

我想如果我在正确的轨道上以及如何继续,或者如果没有,我应该开始在所有decimal属性上放置数据注释.

bri*_*lam 60

你很亲密 这是代码.

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)");
}
Run Code Online (Sandbox Code Playgroud)

注意:如果您有可空类型decimal?,请使用:

Where(p => p.ClrType == typeof(decimal) || p.ClrType == typeof(decimal?))
Run Code Online (Sandbox Code Playgroud)

  • 3小时前我开始输入所有200个房产时你在哪里?:d (10认同)
  • 我正撞在墙上,因为我之前使用过它并且它起作用了,但突然间它不适用于新的实体类型.结果我的`decimal`类型实际上是一个可以为空的`十进制?`.要设置两者的默认值,请确保使用`Where(p => p.ClrType == typeof(decimal)|| p.ClrType == typeof(decimal?))匹配两种类型 (7认同)
  • 有没有办法以强类型方式设置精度?是否有任何 `HasPrecision` 流畅的方法? (3认同)
  • @Shimmy 还没有。按问题 [#11614](https://github.com/aspnet/EntityFrameworkCore/issues/11614) 跟踪。 (2认同)
  • 这工作得很好,但 EFCore3 中出现了问题 - 现在获取“IMutableProperty”不包含“Relational”的定义,并且找不到接受“IMutableProperty”类型的第一个参数的可访问扩展方法“Relational”(您是吗?缺少 using 指令或程序集引用?)`。有人知道我错过了什么吗? (2认同)