【】设置EntityFramework中decimal类型数据精度EF中默认的decimal数据精度为两位数,当我们数据库设置的精度⼤于2时,EF将只会保留到2为精度。
< 2.1999将会被保存为2.20
⽹上找到常见的⽅法为重写DbContext的OnModelCreating⽅法:
1protected override void OnModelCreating(DbModelBuilder modelBuilder)
2{
3 modelBuilder.Entity<Product>().Property(x => x.Price).HasPrecision(18, 4);
4}
但如果数据表多或者Decimal类型字段多的话,⽤OnModelCreating的⽅法将会变得相当冗余,⽽且不便管理。
我推荐使⽤Attribute属性标签进⾏设置,在Entity Model class中decimal的字段上⽅直接添加⾃定义拓展的属性标签即可。
<
其中 [DecimalPrecision(18, 4)]即是我们⾃定义的精度Attribute
具体实现代码如下:
1 1 /// <summary>
素甲2 2 /// <para>⾃定义Decimal类型的精度属性</para>
3 3 /// </summary>
安慰用英语怎么说4 4 [AttributeUsage(AttributeTargets.Property, Inherited = fal, AllowMultiple = fal)]
5 5 public aled class DecimalPrecisionAttribute : Attribute
6 6 {
司马迁与史记7 7
8 8 #region Field
9 9 private byte _precision = 18;
1010 public byte _scale = 4;
1111 #endregion
1212
1313 #region Construct
1414 /// <summary>
1515 /// <para>⾃定义Decimal类型的精确度属性</para>
1616 /// </summary>1984年属相
1717 /// <param name="precision">precision
1818 /// <para>精度(默认18)</para></param>
1919 /// <param name="scale">scale
2020 /// <para>⼩数位数(默认4)</para></param>
2121 public DecimalPrecisionAttribute(byte precision = 18, byte scale = 4)
2222 {
2323 Precision = precision;
2424 Scale = scale;
2525 }
大腿内侧抽筋应急处理2626 #endregion
2727
2828 #region Property
毛寸发型
2929 /// <summary>
3030 /// 精确度(默认18)
3131 /// </summary>
3131 /// </summary>
3232 public byte Precision
3333 {
3434 get { return this._precision; }
3535 t { this._precision = value; }
3636 }
3737
3838 /// <summary>
3939 /// 保留位数(默认4)
4040 /// </summary>
4141 public byte Scale
4242 {
4343 get { return this._scale; }
4444 t { this._scale = value; }
4545 }
4646 #endregion
4747 }
4848
4949 /// <summary>
5050 /// ⽤于modelBuilder全局设置⾃定义精度属性
5151 /// </summary>
5252 public class DecimalPrecisionAttributeConvention
5353 : PrimitivePropertyAttributeConfigurationConvention<DecimalPrecisionAttribute>
5454 {
5555 public override void Apply(ConventionPrimitivePropertyConfiguration configuration, DecimalPrecisionAttribute attribute)
5656 {
5757 if (attribute.Precision < 1 || attribute.Precision > 38)
5858 {
5959 throw new InvalidOperationException("Precision must be between 1 and 38.");
6060 }
歌曲串词
6161 if (attribute.Scale > attribute.Precision)
6262 {
6363 throw new InvalidOperationException("Scale must be between 0 and the Precision value.");
社会实践是什么
6464 }
6565 configuration.HasPrecision(attribute.Precision, attribute.Scale);
6666 }
6767 }
再在DbContext重写OnModelCreating,添加⾃定义的DecimalPrecisionAttributeConvention即可以⽅便地任意添加需要精度控制的字段。
1 public class Project_DbContext : DbContext
2 {
3 public Project_DbContext() : ba("DefaultConnection") { }
4
5 protected override void OnModelCreating(DbModelBuilder modelBuilder)
6 {
7 modelBuilder.Conventions.Add(new DecimalPrecisionAttributeConvention());
8 ba.OnModelCreating(modelBuilder);
9 }
10
11 }