core model four decimal places validation c# data-annotations entity-framework-core


In my model in 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
            .SelectMany(t => t.GetProperties())
            .Where(p => p.ClrType == typeof(decimal) ||
            p.ClrType == typeof(decimal?))
            .Select(p => modelBuilder.Entity(p.DeclaringEntityType.ClrType).Property(p.Name))
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)
            .Property(p => p.GoalDiameterTolerance)
            .HasPrecision(18, 4); 
9/25/2017 9:30:21 PM

Related Questions


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