【问题标题】:asp.net core model four decimal places validationasp.net核心模型四位小数验证
【发布时间】:2017-09-25 19:34:43
【问题描述】:

在我的 asp.net 核心模型中,当我搭建数据库时,它只允许一个带有两个小数位的数字,例如 0.10,但是我不允许在我的数据库中插入四个小数位。

下面是我的模型。

     public class Order
{
    public int OrderID { get; set; }

    [RegularExpression(@"^\d+.\d{0,4}$", ErrorMessage = "Must have four decimal places")]
    [Range(0.0001, 1)]
    [Display(Name = "Goal Diameter Tolerance")]
     public decimal? GoalDiameterTolerance { get; set; }
}

下面是脚手架的 GoalDiameterTolerance。它只允许两位小数。我可以更改它,但是如何在模型中的脚手架之前修复它。

 GoalDiameterTolerance = table.Column<decimal>(type: "decimal(18, 2)", nullable: true),

我相信它应该为此提供支架。

GoalDiameterTolerance = table.Column<decimal>(type: "decimal(18, 4)", nullable: true),

这是我解决问题的方法。

foreach (var property in modelBuilder.Model
            .GetEntityTypes()
            .SelectMany(t => t.GetProperties())
            .Where(p => p.ClrType == typeof(decimal) ||
            p.ClrType == typeof(decimal?))
            .Select(p => modelBuilder.Entity(p.DeclaringEntityType.ClrType).Property(p.Name))
            )
        {
            property.HasColumnType("decimal(18,4)");
        }

【问题讨论】:

  • [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:#.####}")] 是另一种可能行不通的方法。

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


【解决方案1】:

我认为 EF 代码生成不会尝试从 Display\Validation 属性推断列类型。您应该能够使用 Column 属性显式指定所需的列类型

Column(TypeName = "decimal(18, 4)")

或者通过覆盖 OnModelCreating 并在那里自定义您的列类型

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
     modelBuilder.Entity<Order>()
            .Property(p => p.GoalDiameterTolerance)
            .HasPrecision(18, 4); 
}

【讨论】:

猜你喜欢
  • 2021-09-13
  • 2019-10-01
  • 1970-01-01
  • 2017-01-04
  • 2017-05-13
  • 2019-08-05
  • 2021-06-26
  • 1970-01-01
  • 2020-12-03
相关资源
最近更新 更多