2

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

Henrik
  • 63
  • 1
  • 6

1 Answers1

4

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);
    }
}
Steve Greene
  • 12,029
  • 1
  • 33
  • 54
  • Hi, this saved my day. The TruncateDecimalsToScale = false solved the problem. I think I did try this yesterday, but must have made some mistake. I tried to upvote your answer, but I do not have enough reputation for that to show. – Henrik May 31 '17 at 07:11
  • Can you please give more details on how you assigned this to the context you use? – Andrew Dec 01 '17 at 14:49
  • See [here](https://msdn.microsoft.com/en-us/library/jj680699(v=vs.113).aspx). I just added it as a class in same folder as context. – Steve Greene Dec 01 '17 at 15:10
  • The above didn't work for me in the latest version of EF Core 6. However, here is the answer that I used. https://stackoverflow.com/a/43282620/13590277 – SakerCobalt Jul 15 '22 at 14:38