Entity Framework Decimal Truncation Issue

c# decimal ef-code-first entity-framework entity-framework-6


The project I'm working on uses Entity Framework 6.0 Code-First.

One of my co-workers, due to his lack of experience with EF, manually changed the field type of a field on the database to being decimal(28,10), instead of doing it the correct way in the OnModelCreating method of DbContext. Entity Framework allowed him to do so, never throwing an error upon any future migrations.

Last week, another co-worker was running into a problem with a process that clones records from that table, where the decimal values in the new records were being truncated to 2 decimal places (with no rounding occurring).

The code for that cloning resembles the following (using the Repository pattern on top of EF):

public void CloneAccounts(List<Account> accounts, int newQuarterID)
    var newAccounts = new List<Account>();
    accounts.ForEach(account =>
        var clonedAccount = new Account
            QuarterID = newQuarterID
            AccountName = account.AccountName,
            AccountNumber = account.AccountNumber,
            Amount = account.Amount



When I pointed out, as a side-point, that the declaration of the Amount field being decimal(28,10) should really be in OnModelCreating, he went ahead and did that, and added a migration. Doing that, interestingly enough, ended up solving the issue with the code above.

My question is two-fold:

  1. Why did that issue not affect the creation of the original records as well, and only upon cloning?
  2. Why did adding that line in OnModelCreating fix it?


6/8/2015 4:02:41 PM

Popular Answer

If you didn't originally have any precision set, the default convention for code-first is to create decimal columns with precision of 18 and scale of 2 (so only two decimal places). I think it's possible the records had originally been truncated in the first place.

Also, by default, the SQL Server provider's SQL generator sets SqlParameter.Scale property to the scale defined in the model, unless you had TruncateDecimalsToScale set to false, which would affect database updates and inserts. I'm not sure how those records with additional decimal places ended up in the database, though.

6/8/2015 8:25:30 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow