Savechanges is truncating the decimal value

Asked

Viewed 111 times

2

I’ll rephrase the question: I need to write to the database with four decimal places. For example. In the view I type a percentage value of 56.78%. In the bank should be recorded 0.5678. That’s why the field is Top 18,4, this is standard for decimal fields here in the company. In the application and in the database, the fields are thus(18,4). It turns out that when I write a decimal value, as in the example above, it is truncating the decimal part, recording only 0.5600 and not 0.5678. I’ve gone through the system to try to figure out where it’s being truncated and even the savechanges() i have 0.5678. After that, when I am redirected to the Index, it appears 56,00 and not 56,78. When running the SaveChages() I run the select right at the bank and have there 0.5600. How to solve this

In the debug output I take this in SaveChanges()

INSERT [dbo].[AzureDiscountGroup]([Id], [Descricao], [PercDesconto])
VALUES (@0, @1, @2)

-- @0: '19' (Type = Int32)

-- @1: 'FFF' (Type = String, Size = 50)

-- @2: '0,3497' (Type = Decimal, Precision = 18, Scale = 2)

Note that Scale is 2 and not 4. How do I change this?

  • 1

    the discount is divided by 100 in the following row model.PercDesconto = model.PercDesconto / 100;

  • As the colleague commented... because you are dividing the value by 100?

  • @Leandroangelo, returning today after 3 days at home. It is divided by 100, to record in the bank 35,56% in the bank would be 0.3556. And to show on screen should take the bank multiply by 100 to stay 35,56

  • So what is the doubt and why the field is decimal(18,4) in the bank? None of this question makes sense.

1 answer

2


What’s going on?

Entity Framework by default handles decimal with precision 2.

How to solve

public class EFDbContext : DbContext
{
   protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
   {
       modelBuilder.Entity<Class>().Property(object => object.property).HasPrecision(12, 4);

       base.OnModelCreating(modelBuilder);
   }
}

More information can be found here:

EF decimal Scale and Precision Convention

Decimal Precision EF codefirst

  • I already did in Mapping, exactly as Ronaldo replied. As I did not answer before, I will mark Ronaldo’s as correct.

Browser other questions tagged

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