3

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:

  • Including modelBuilder.Conventions.Remove<DecimalPropertyConvention>() in the OnModelCreating method, to remove the 18,2 decimal convention altogether. Same exception as above
  • Building the latest source code from scratch, and changing the default scale to 4 in the DecimalPropertyConvention class. Same exception.
Community
  • 1
  • 1
HiredMind
  • 1,827
  • 17
  • 27
  • If you change anything in model mapping or remove default convention you must also create a new migration. Did you try it? – Ladislav Mrnka Aug 23 '12 at 21:18
  • Hmm, I didn't think of that. Trying it now... – HiredMind Aug 23 '12 at 21:33
  • That worked. I guess I didn't realize that OnModelCreating was examined for changes for migration purposes. I thought it was just a hook to tweak something before the model is created. If you post an answer I'll give credit for it - I think others might be unclear on the nature of this method. – HiredMind Aug 23 '12 at 21:42

1 Answers1

2

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.

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670