C# MVC5 - Insert Fields with 4 Decimal Digits

Asked

Viewed 400 times

3

I am making an entry in the database (SQL Server 2008) of a field configured to 'decimal(10,4)', from which I try to insert/edit, by my application C# MVC5, a field of 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, e.g.: 0.8999. However, when I do Savechanges it ends up recording in the database as follows '0.8900'.

I am using EF 6.1.3 with reverse engineering to generate the models (Dbfirst). When I enter the command below in my context class that 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.

2 answers

1


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

Do not forget to register the ModelBinder in the 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();

        ...
     }
}
  • This 'Decimalmodelbinder' I would implement where? Because if I have to implement in my context class, it will be deleted every update of the classes (via Dbfirst)...

  • There is no way for me to create an auxiliary 'Onmodelcreating', and only complement this method with some lines of code adding to the 'Onmodelcreating' of the context class?

  • @Antôniofilho I wear one namespace of the kind: MeuProjeto.Infrastructure.ModelBinders. Then you do not run the risk of being deleted. It is up to you. Note that a model Binder no need to accompany the Code First simply because it is part of the application, and not the bank, this conversion.

  • Even if this answer was accepted I don’t understand how it helps the AP. AP clearly states that the value is correctly assigned to the property before writing to the database. Therefore the problem cannot be related to bindings

  • I noticed now that it is already 3 years old and therefore my vote does not even make sense. I am sorry

0

When I enter the command below in my context class that is automatically generated, works normally, but I have to change every time the database is updated.

You should not modify the code of your context once it is generated automatically. If you need to make changes to your context do it in a separate file. Note that the context is generated with keyword partial. This allows you to implement logic in a different file that is never modified by automatic code generator.

partial public OMeuContexto{

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Class>().Property(o => o.property).HasPrecision(12, 10);
    }
}

Once again I draw attention. Do this in another file that is not automatically generated

Browser other questions tagged

You are not signed in. Login or sign up in order to post.