MSSQL四舍五入小数

时间:2020-05-18 17:27:02

标签: c# sql-server entity-framework

我的数据库有问题。 我正在尝试在表格的十进制列中保存一个十进制值。这就是我要添加的值的方式:

Image img = Image.FromFile(Server.MapPath("~/Files/Galleries/" + foto.Gallery + "/" + newFile));
foto.AspectRatio = (decimal)img.Width / (decimal)img.Height;

此时,值将类似于0.834231235232。但是在保存数据库时,它将四舍五入到小数点后两位0.8300000000。 小数位数和精度设置为decimal(18,18)

为什么会这样?可能是实体框架失去了这些多余的小数点吗?

1 个答案:

答案 0 :(得分:0)

如果您在c#中的字段是decimal类型,则默认情况下它将像数据库中的decimal(18,2)一样工作,但是您可以这样覆盖它:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<NameOfEntity>()
                .Property(p => p.NameOfProperty)
                .HasPrecision(18, 18); // or whatever your schema specifies
}