What's the best way of specifying a decimal precision without using attributes. I just need to set it in one place for all decimal's in my Data.Models. Its tedious specifying attributes for every decimal.
public class Customer
{
public int customerId { get; set; }
[Column(TypeName = "decimal(18,2)")]
public decimal AvailableAmount { get; set; }
}
I experienced this issu using ASP.NET CORE 5. I added the folowing code to the OnModelcreating method in the DbContext.
protected override void OnModelCreating(ModelBuilder modelBuilder)// Crée la migration
{
modelBuilder.Entity<MyEntity>().Property(p => p.Prix).HasColumnType("decimal(18,4)");
}
And all started working fine.
Add following to the OnModelCreating
method in the dbcontext:
protected override void OnModelCreating(ModelBuilder builder)
{
foreach (var property in builder.Model.GetEntityTypes()
.SelectMany(t => t.GetProperties())
.Where(p => p.ClrType == typeof(decimal) || p.ClrType == typeof(decimal?)))
{
property.Relational().ColumnType = "decimal(18,2)";
}
}
For those who are struggling with the same issue on EntityFrameworkCore 6.0, this will do it:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var decimalProps = modelBuilder.Model
.GetEntityTypes()
.SelectMany(t => t.GetProperties())
.Where(p => (System.Nullable.GetUnderlyingType(p.ClrType) ?? p.ClrType) == typeof(decimal));
foreach (var property in decimalProps)
{
property.SetPrecision(18);
property.SetScale(2);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With