EF Code First 中的小数精度和小数位数 [英] Decimal precision and scale in EF Code First

查看:106
本文介绍了EF Code First 中的小数精度和小数位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试这种代码优先的方法,但我现在发现 System.Decimal 类型的属性被映射到 decimal(18, 0) 类型的 sql 列.

I'm experimenting with this code-first approach, but I'm find out now that a property of type System.Decimal gets mapped to a sql column of type decimal(18, 0).

如何设置数据库列的精度?

How do I set the precision of the database column?

推荐答案

Dave Van den Eynde 的回答现已过时.有 2 个重要变化,从 EF 4.1 开始,ModelBuilder 类现在是 DbModelBuilder 现在有一个 DecimalPropertyConfiguration.HasPrecision 方法,其签名为:

The answer from Dave Van den Eynde is now out of date. There are 2 important changes, from EF 4.1 onwards the ModelBuilder class is now DbModelBuilder and there is now a DecimalPropertyConfiguration.HasPrecision Method which has a signature of:

public DecimalPropertyConfiguration HasPrecision(
byte precision,
byte scale )

其中 precision 是 db 将存储的总位数,无论小数点在哪里,scale 是它将存储的小数位数.

where precision is the total number of digits the db will store, regardless of where the decimal point falls and scale is the number of decimal places it will store.

因此不需要如图所示遍历属性,而是可以从

Therefore there is no need to iterate through properties as shown but the can just be called from

public class EFDbContext : DbContext
{
   protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
   {
       modelBuilder.Entity<Class>().Property(object => object.property).HasPrecision(12, 10);

       base.OnModelCreating(modelBuilder);
   }
}

这篇关于EF Code First 中的小数精度和小数位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆