Entity Framework 6 decimal precision

entity-framework-6

Question

In my code-first entity framework sql database I have a decimal value specified as 18,3. Database object:

public decimal? Kolhalt { get; set; }

In OnModelCreating I have

     modelBuilder.Entity<Skada>().Property(o => o.Kolhalt).HasPrecision(18, 3);

In the database the value is specified as Kolhalt (decimal(18, 3), null)

If I enter a value directly in the database I get three decimals, but when I insert or update a value with EntityFramework it is truncated to 2 decimal places.

With Sql server profiler I can see that EF specifies 2 decimals for the stored value:

[Kolhalt] = @14 ...  @14 decimal(18,2) ...  @14=5.12

(The entered value was 5.123).

So for some reason EF truncates the values sent to the database when I call SaveChanges().

Do I have to specify the number of decimals someplace else to get it right in SaveChanges()?

Best regards, Henrik

1
2
5/30/2017 8:41:54 AM

Accepted Answer

I had a similar problem in a project. Oddly, when I changed my model from decimal? to decimal it started working. I also found a configuration setting TruncateDecimalsToScale which can be added:

public class DbContextConfiguration : DbConfiguration
{
    public DbContextConfiguration()
    {
        var providerInstance= SqlProviderServices.Instance;
        SqlProviderServices.TruncateDecimalsToScale = false;
        this.SetProviderServices(SqlProviderServices.ProviderInvariantName, SqlProviderServices.Instance);
    }
}
4
5/30/2017 2:52:42 PM


Related Questions





Related

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