C# MVC5 – Insert Fields with 4 Decimal Digits

Question:

I'm inserting into the database (SQL Server 2008) a field set to 'decimal(10,4)', which I try to insert/edit, by my C# MVC5 application, a field from my model of type 'decimal '.

The fact is that when I debug the code, even before the time of 'context.SaveChanges()', it has the correct decimal places, eg: 0.8999. However, when I do SaveChanges it ends up writing to the database as follows '0.8900'.

I'm using EF 6.1.3 with reverse engineering to generate the models (DbFirst). When I enter the command below in my context class which is automatically generated, it works normally, but I have to change it every time the database is updated.

modelBuilder.Entity<Class>().Property(object => object.property).HasPrecision(12, 10);

NOTE: All my methods that I need to insert fields in this condition are also not recorded with 4 decimal places, but with only 2.

Answer:

Implement a ModelBinder like this:

public class DecimalModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        object result = null;

        string modelName = bindingContext.ModelName;
        string attemptedValue = bindingContext.ValueProvider.GetValue(modelName).AttemptedValue;

        string wantedSeperator = NumberFormatInfo.CurrentInfo.NumberDecimalSeparator;
        string alternateSeperator = (wantedSeperator == "," ? "." : ",");

        if (attemptedValue.IndexOf(wantedSeperator) == -1
            && attemptedValue.IndexOf(alternateSeperator) != -1)
        {
            attemptedValue = attemptedValue.Replace(alternateSeperator, wantedSeperator);
        }

        try
        {
            // Faça um Debug desta lista. 
            // Se precisar, amplie a lógica dela para aceitar 4 casas.
            result = decimal.Parse(attemptedValue, NumberStyles.Any);
        }
        catch (FormatException e)
        {
            bindingContext.ModelState.AddModelError(modelName, e);
        }

        return result;
    }
}

Don't forget to register the ModelBinder at Global.asax.cs :

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        ...

        ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
        ModelBinders.Binders.Add(typeof(decimal?), new DecimalModelBinder());
        ModelBinders.Binders.DefaultBinder = new CustomModelBinder();

        ...
     }
}
Scroll to Top