Entity Framework DecimalPropertyConvention


Example

By default Entity Framework maps decimal properties to decimal(18,2) columns in database tables.

public class Box
{
    public int Id { set; get; }
    public decimal Length { set; get; }
    public decimal Width { set; get; }
    public decimal Height { set; get; }
}

enter image description here

We can change the precision of decimal properties:

1.Use Fluent API:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Box>().Property(b => b.Width).HasPrecision(20, 4);
}

enter image description here

Only "Width" Property is mapped to decimal(20, 4).

2.Replace the convention:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Remove<DecimalPropertyConvention>();
    modelBuilder.Conventions.Add(new DecimalPropertyConvention(10, 4));
}

enter image description here

Every decimal property is mapped to decimal(10,4) columns.