Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set decimal precision and scale in entity framework code first migrations

I am using entity framework migrations and need to set the precision and scale of a decimal property in an entity. I only want to do this for this single decimal property not all decimal properties. I've already overridden the OnModelCreating method to set decimal to (18, 2) by default. I need this one property to be (22,5). So for example,

public class AdditionalCharge
{
  public decimal? Rate { get; set; }
}

gets created in the database as a "decimal (18,2) NULL" column. I need it to become a "decimal (22,5) NULL" column.

I can create an empty migration and hand code the change,

public override void Up()
{
  AlterColumn("dbo.AdditionalCharge", "Rate", c => c.Decimal(nullable: true, precision: 22, scale: 5));
}

but I'd rather just change the C# declaration and let migrations create the change.

Is there a way to do that?

Mike

like image 359
Mike Lockhart Avatar asked Sep 13 '25 14:09

Mike Lockhart


1 Answers

You can set the precision of the column in OnModelCreating as well:

modelBuilder.Entity<AdditionalCharge>().Property(o => o.Rate ).HasPrecision(22, 5);

But I don't know whether or not the change will be picked up in the migration.

like image 167
D Stanley Avatar answered Sep 16 '25 04:09

D Stanley