Loss of Precision from C# to SQL Server
This is an issue I am facing which is causing loss of precision when storing in SQL Server database from C# Entity Framework.
decimal(20, 15)
public decimal AssignedGrossBudget { get; set; }
public decimal AssignedGrossBudget { get; set; }
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 directly inserting in the table and it works.
A simple example shows that no such loss of precision occurs 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 the problem is with your code, which is not posted.
Thanks Urril and Remus.
I make changes in Entity Framework as below:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<StationMapping>().Property(x => x.AssignedGrossBudget).HasPrecision(35, 15);
}
And for SQL BulkCopy I added Data Type as per Remus suggestion.
SpotLookupTable.Columns.Add(new DataColumn("GrossBudget",typeof(decimal)));
Its is working now and there is no loss (or Negligible).
Cheers
链接地址: http://www.djcxy.com/p/19664.html上一篇: 在Instagram上发布视频
下一篇: 从C#到SQL Server的精度损失