Loss of precision from C # to SQL Server

This is a problem that I am facing that causes a loss of precision when stored in a SQL Server database from the C # Entity Framework.

  • SQL Server decimal(20, 15) data type decimal(20, 15)
  • In C #, a Property is defined as public decimal AssignedGrossBudget { get; set; } public decimal AssignedGrossBudget { get; set; }
  • in C # value in variable (AssignedGrossBudget) - 34.09090909090909
  • But in the SQL Server table, this is 34.090000000000000

What could be wrong? (I am using Entity Framework db.SaveChanges () and SQLBulkCopy to store data from C # to SQL Server)

I want to store 34.09090909090909 instead of 34.090000000000000.

I checked by inserting directly into the table and it works.

+7
decimal c # sql-server entity-framework sqldatatypes
source share
2 answers

A simple example shows that such a loss of accuracy does not occur with correctly written code:

  static void Main(string[] args) { decimal d = 34.09090909090909M; Console.WriteLine(d); SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder(); scsb.IntegratedSecurity = true; scsb.DataSource = @".\sql2012"; using (SqlConnection conn = new SqlConnection(scsb.ConnectionString)) { conn.Open(); using (SqlCommand cmd = new SqlCommand( "select cast(@d as DECIMAL(20,15))", conn)) { cmd.Parameters.AddWithValue("@d", d); decimal rd = (decimal) cmd.ExecuteScalar(); Console.WriteLine(rd); } } } 

Therefore, I must conclude that the problem is with your code that is not submitted.

+1
source share

Thanks to Urril and Remus.

I am making changes to the Entity Framework as shown below:

 protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<StationMapping>().Property(x => x.AssignedGrossBudget).HasPrecision(35, 15); } 

And for SQL BulkCopy, I added a data type as suggested by Remus.

 SpotLookupTable.Columns.Add(new DataColumn("GrossBudget",typeof(decimal))); 

Now it works, and there are no losses (or insignificant).

Greetings

+2
source share

All Articles