背景 工作需要配置多個環境,用於 開發Development、預覽Staging、生產Production。 參考文獻: 微軟官方文檔-配置 開始 .NetCore對多環境有很好的支持,預設會讀取appsettings.{Environment}.json。 例如,appsettings.Produ ...
EF中預設的decimal數據精度為兩位數,當我們資料庫設置的精度大於2時,EF將只會保留到2為精度。
如 product.Price=0.0111,存到資料庫會變成0.0100
1.解決方案一是網上找到常見的方法為重寫DbContext的OnModelCreating方法:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>().Property(x => x.Price).HasPrecision(18, 5);
}
但如果數據表多或者Decimal類型欄位多的話,用OnModelCreating的方法將會變得相當冗餘,而且不便管理。
2.解決方案二是我推薦使用Attribute屬性標簽進行設置,在Entity Model class中decimal的欄位上方直接添加自定義拓展的屬性標簽即可。
調用:
其中 [DecimalPrecision(18, 5)]即是我們自定義的精度Attribute
具體實現代碼如下:
/// <summary>
/// <para>自定義Decimal類型的精度屬性</para>
/// </summary>
[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
public class DecimalPrecisionAttribute : Attribute
{
#region Field
private byte _precision = 18;
public byte _scale = 5;
#endregion
#region Construct
/// <summary>
/// <para>自定義Decimal類型的精確度屬性</para>
/// </summary>
/// <param name="precision">precision
/// <para>精度(預設18)</para></param>
/// <param name="scale">scale
/// <para>小數位數(預設5)</para></param>
public DecimalPrecisionAttribute(byte precision = 18, byte scale = 5)
{
Precision = precision;
Scale = scale;
}
#endregion
#region Property
/// <summary>
/// 精確度(預設18)
/// </summary>
public byte Precision
{
get { return this._precision; }
set { this._precision = value; }
}
/// <summary>
/// 保留位數(預設5)
/// </summary>
public byte Scale
{
get { return this._scale; }
set { this._scale = value; }
}
#endregion
}
/// <summary>
/// 用於modelBuilder全局設置自定義精度屬性
/// </summary>
public class DecimalPrecisionAttributeConvention
: PrimitivePropertyAttributeConfigurationConvention<DecimalPrecisionAttribute>
{
public override void Apply(ConventionPrimitivePropertyConfiguration configuration, DecimalPrecisionAttribute attribute)
{
if (attribute.Precision< 1 || attribute.Precision> 38)
{
throw new InvalidOperationException("Precision must be between 1 and 38.");
}
if (attribute.Scale > attribute.Precision)
{
throw new InvalidOperationException("Scale must be between 0 and the Precision value.");
}
configuration.HasPrecision(attribute.Precision, attribute.Scale);
}
}
再在DbContext重寫OnModelCreating,添加自定義的DecimalPrecisionAttributeConvention即可以方便地任意添加需要精度控制的欄位。
public class Project_DbContext : DbContext
{
public Project_DbContext() : base("DefaultConnection") { }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Add(new DecimalPrecisionAttributeConvention());
base.OnModelCreating(modelBuilder);
}
}
轉載於:https://www.cnblogs.com/lonelyxmas/p/9962627.html