Home > Software design >  Setting all decimal properties to the same precision in entity framework
Setting all decimal properties to the same precision in entity framework

Time:11-19

I am trying to find a way of setting the precision for every decimal property in our entities to be different from the entity framework standard but with little success.

Our standard for our decimal precision is 18, 6, which is different from the entity framework standard of 14, 2. We do currently set it for every property like this:

modelBuilder.Entity<Entity>().Property(x => x.Property).HasPrecision(18, 6); 

but we want to move away from doing this for every decimal as its always set to the same and sometimes gets missed (we've recently spent a lot of time going back and adding these in for properties that we missed and therefore is having data saved to 2 decimal places rather than 6)

Any help would be greatly appreciated!

The only solution I have at the moment is to create an overloaded method that looks like this so we always set the precision and scale to the same values:

public static void HasPrecision(this DecimalPropertyConfiguration decimalPropertyConfiguration, byte precision = 18, byte scale = 6)
{
    decimalPropertyConfiguration.HasPrecision(precision, scale);
}

But this means we still have to call this for every decimal property in the same way we did before so provides little benefit to us moving forward

CodePudding user response:

In EF6 this behavior is controlled by DecimalPropertyConvention. That means you can remove that convention and then add back but with the values you need:

modelBuilder.Conventions.Remove<DecimalPropertyConvention>();
modelBuilder.Conventions.Add(new DecimalPropertyConvention(18, 6));
  • Related