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

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

问题描述

我正在尝试使用这种代码优先的方法,但是现在我发现System.Decimal类型的属性映射到十进制(18,0)类型的sql列。



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

解决方案

Dave Van den Eynde的答案现在已经过时了。有两个重要的变化,从EF 4.1起,ModelBuilder类现在是 DbModelBuilder ,现在有一个DecimalPropertyConfiguration.HasPrecision方法,它具有以下签名:

  public DecimalPropertyConfiguration HasPrecision(
byte precision,
byte scale)

其中precision是db将存储的总位数,而不管小数点在哪里,scale是存储的小数位数。



因此,不需要遍历所示的属性,但是可以从

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

base.OnModelCreating(modelBuilder);
}
}


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?

解决方案

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 )

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天全站免登陆