0

In my model in asp.net core when I scaffold my database it only allows for a number with two decimal places like 0.10 but, I am not allowed to insert four decimal places into my database.

Below is my model.

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

Below is the GoalDiameterTolerance scaffolded. It only allows for two decimal places. I can change it but, how do I fix it before the scaffold in the model.

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

It should scaffold to this I believe.

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

Here is how I solved my problem.

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

1 Answers1

0

I do not think EF code generation tries to deduce the column type from Display\Validation attributes. You should be able to specify the desired column type explicitly using the Column attribute

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

Or by overriding OnModelCreating and customize your column type there

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