EF Core decimal 类型设置精度

[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
public class DecimalPrecisionAttribute : Attribute
{
    #region Field
        private byte _precision = 18;
        public byte _scale = 2;
        #endregion

    #region Construct
    /// 
    /// 自定义Decimal类型的精确度属性
    /// 
    /// precision
    /// 精度(默认18)
    /// scale
    /// 小数位数(默认2)
    public DecimalPrecisionAttribute(byte precision = 18, byte scale = 2)
    {
        Precision = precision;
        Scale = scale;
    }
    #endregion

    #region Property
    /// 
    /// 精确度(默认18)
    /// 
    public byte Precision
    {
        get { return this._precision; }
        set { this._precision = value; }
    }

    /// 
    /// 保留位数(默认2)
    /// 
    public byte Scale
    {
        get { return this._scale; }
        set { this._scale = value; }
    }
    #endregion
}

重写xxDbContext类 OnModelCreating 方法 

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    foreach (var item in modelBuilder.Model.GetEntityTypes())
    {
        var type = item.ClrType;
        var props = type.GetProperties().Where(c => c.IsDefined(typeof(DecimalPrecisionAttribute), true)).ToArray();
        foreach (var p in props)
        {
            var precis = p.GetCustomAttribute();
            modelBuilder.Entity(type).Property(p.Name).HasColumnType($"decimal({precis.Precision},{precis.Scale})");
        }
    }
    base.OnModelCreating(modelBuilder);
}

运行 AddMigration 命令生成如下脚本

EF Core decimal 类型设置精度_第1张图片

你可能感兴趣的:(.NET,CORE)