简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM