C# Entityframework, mssql, decimal精準度問題

C# Entityframework, mssql, decimal精準度問題

This is because Entity Framework, by default, maps the .NET decimal type to SQL Server's decimal(18,2) data type, which might not match the precision and scale you require for your specific use case.

由於Entity Framework, .Net decimal型別, 預計對應MSSQL decimal型別的精準度為decimal(18, 2), 所以當C#寫入資料包含小數第3位時, 寫入資料庫後會被截掉。

解決方案如下,

使用Fluent API:如果您使用的是Entity Framework 6,您可以在OnModelCreating方法中使用Fluent API來設定資料庫欄位的精確度和小數位數

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    //指定所有decimal欄位轉換
    modelBuilder.Properties<decimal>().Configure(config => config.HasPrecision(18, 5));

    //指定特定欄位轉換
    modelBuilder.Entity<YourEntity>().Property(e => e.YourDecimalProperty).HasPrecision(18, 5);
}

若為 Entity Framework Core, 也可使用下面2個寫法 (未實際驗證過是否可行)

public Class YourEntity
{
  [Column(TypeName = "decimal(18,5)")]
  public decimal YourDecimalProperty {get; set;}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<YourEntity>()
        .Property(e => e.YourDecimalProperty)
        .HasColumnType("decimal(18,5)");
}

 

留言

這個網誌中的熱門文章

ORA-12514: TNS: 監聽器目前不知道連線描述區中要求的服務

Oracle 例外控制(Exception Control)

Oracle 工作排程 DBMS_JOB 筆記