HiredMind
HiredMind

Reputation: 1857

EF5 code first migrations: decimal precision and scale

I'm trying to use code-first on an existing Point-Of-Sale kiosk application. This is a fuel station app, so I need to use currencies with three digits after the decimal point.

I'm using the following code in my migrations to set the precision and scale:

CustomSqlGenerator.DropDefaultConstraint("Config", "DefaultTaxPerDollar", q => Sql(q));
    AlterColumn("Config", "DefaultTaxPerDollar", c => c.Decimal(nullable: false, precision: 19, scale: 4, defaultValue: 0.087m));

(The DropDefaultConstraint call is a workaround for this bug. I've tried removing it - creating the column in the initial migration instead of altering it later - to no avail.)

And the column is created with the proper precision and scale. I can use SSMS to enter values properly (i.e. 1.2345 is saved as 1.2345). But when values are saved through the model, all values are truncated - not rounded - to 2 decimal places (e.g. 0.5555 becomes 0.55).

The first thing I tried was using the Fluent API in the OnModelCreating method as shown here:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity()
        .Property(c => c.DefaultTaxPerDollar)
        .HasPrecision(19, 4);

    base.OnModelCreating(modelBuilder);
}

But that produces The model backing the 'SalesDataStore' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269)

Also tried:

Upvotes: 3

Views: 2531

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364319

Mapping defines your model. Each migration stores the compressed XML representation of the model (and probably also hash). When you change anything in the mapping including removing any default convention you also change the final XML representation of the mapping and its hash. EF uses those hashes to check if model changed or not - if you change the model you must also have a new migration to make it work.

Upvotes: 2

Related Questions