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

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

  • 有什么事吗(我正在使用Entity Framework db.SaveChanges();和SQLBulkCopy将数据从C#存储到SQL Server)

    我想存储34.09090909090909而不是34.090000000000000。

    我通过直接插入表中进行检查,它可以工作。

    最佳答案

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

        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);
                }
            }
        }
    

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

    07-24 09:37
    查看更多