C# Tips

C# Tip Article

How to use Decimal data type in Entity Framework (EF and EFCore)

In Entity Framework, "decimal" has 0 in its scale by default. For example, if you save 0.414213 onto deciaml column (of table) in C#, it will truncate .414213 and store only 0 onto the column in DB. Even if your column type of the table is decimal(18, 8) in DB, EF will truncate any value under decimal point first and then save the value to the column. So it will be truncated.

In case of Entity Framework

To resolve the issue in Entity Framework, we can use HasPrecision() in OnModelCreating() method. If decimal column is deciaml(18, 8) (precision: 18, scale: 8), we can call HasPrecision(18, 8) as shown below.

    [Table("Tab")]
    public class Tab
    {
        [Key]
        [Required]
        public int Id { get; set; }   

		public decimal Amount { get; set; }
    }

	public class MyDbContext : DbContext
    {
		// ... 

		protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            // EF decimal will map to TSQL decimal(18,0). 
            // If this is not defined, decimal scale value will be zero. (ex) 0.01234 => 0            
            modelBuilder.Entity<Tab>().Property(p => p.Amount).HasPrecision(18, 8);

            base.OnModelCreating(modelBuilder);
        }

		public DbSet<Tab> Tabs { get; set; }
	}

In case of Entity Framework Core

To resolve the issue in Entity Framework Core (EFCore), we can add [Column(TypeName = "decimal(18,8)")] annotation on deciaml property.

    [Table("Tab")]
    public class Tab
    {
        [Key]
        [Required]
        public int Id { get; set; }   

		[Column(TypeName = "decimal(18,8)")]
		public decimal Amount { get; set; }
    }