If you save a Decimal value to SQLServer, it will only save up to two decimal places.

Asked 2 years ago, Updated 2 years ago, 92 views

  • EntityFramework Version=6.0.0.0
  • .Net Framework targetFramework="4.6.1"
  • SQL Server Express 13.0.4001.0

In the table on SQL Server, there is a column created with Decimal (12,3) and Decimal (18,3) that is being updated using Linq.

decimal?d12=123.456m;
decimal?d18 = 222.222m;
Record rec=DbContext.Table.Where(a=>a.id==1).First();
rec.dec12_3col=d12;
rec.dec18_3col=d18;
DbContext.SaveChanges();

After the update, I checked the data in SQL Server Management Studio and found that dec12_3col contains 123.450 and dec18_3col contains 222.220 and the third decimal place was truncated.

Even if you look at the rec in the debugger before calling SaveChanges, you can see that the values are set to three decimal places, so I don't know where to fix them.

Thank you for your cooperation.

c# sql-server linq entity-framework

2022-09-30 14:33

2 Answers

I was able to solve this problem by describing the accuracy in DbContext.

public partial class ProjectDbContext:DbContext
{
    protected override void OnModelCreating (DbModelBuilder modelBuilder)
    {
            modelBuilder.Entity<Table>()
                .Property(e=>e.dec12_3col)
                .HasPrecision (12,3);

            modelBuilder.Entity<Table>()
                .Property(e=>e.dec18_3col)
                .HasPrecision (18,3);
    }
}

This fix now sets the third decimal place successfully.


2022-09-30 14:33

The reason is that if you don't place anything, it will be used as SQL's Decimal default accuracy (18,2).

I don't know how to configure the program, so I think I can improve it by adding the following code to the placement file.

<Property Name="dec12_3col" Type="decimal" Precision="12" Scale="3" Nullable="false"/>
<Property Name="dec18_3col" Type="decimal" Precision="18" Scale="3" Nullable="false"/>


2022-09-30 14:33

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.