从C#到SQL Server的精度损失

use*_*418 7 c# sql-server entity-framework decimal sqldatatypes

这是我面临的一个问题,当从C#Entity Framework存储在SQL Server数据库中时会导致精度损失.

  1. SQL Server数据类型是 decimal(20, 15)
  2. 在C#中,属性定义为 public decimal AssignedGrossBudget { get; set; }
  3. 在C#中的变量值(AssignedGrossBudget)是34.09090909090909
  4. 但在SQL Server表中它是34.090000000000000

可能有什么不对?(我使用实体框架db.SaveChanges();和SQLBulkCopy将数据从c#存储到SQL Server)

我想存储34.09090909090909而不是34.090000000000000.

我通过直接插入表中检查它是否有效.

Rem*_*anu 1

一个简单的例子表明,正确编写的代码不会发生这种精度损失:

    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);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

因此,我必须得出结论,问题出在您的代码上,该代码未发布。