asp.net core model four decimal places validation

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

Question

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
0
9/25/2017 9:42:07 PM

Popular Answer

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); 
}
0
9/25/2017 9:30:21 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow