Search code examples
c#sql-serverentity-frameworksql-server-2019

Entity Framework truncating decimal places when updating table


I have a table with a decimal(18, 3) column. The table maps to a class with the corresponding decimal property.

I change the value of the property to, e.g. 0.035, and this is the command that is generated by EF to update the column:

exec sp_executesql N'UPDATE [dbo].[mytable]
SET [mycolumn] = @0
WHERE ([id] = @1)
',N'@0 decimal(18,2),@1 int',@0=3,@1=3

I need the scale to be up to 3 decimal places (which I'm doing) but it gets truncated to 2 on update.

Why is this happening and how can I solve this problem?


Solution

  • You could call HasColumnType("decimal(18,3)") or avoid invoking the HasColumnType() in your OnModelCreating() method where you are configuring each property like this:

      entity.Property(e => e.mycolumn)
        .HasColumnType("decimal")
        .HasDefaultValueSql("00.000");
    

    The EF uses a scale of 2 by default.