4

I've come across the craziest behaviour in an application. I am using EF 6 and have a model with a decimal property, the database type powering is a decimal (18,4). If I change the value of the decimal from 0.6500 to 0.6550 and do save changes on the context, the row is not updated. If I change it from 0.6500 to 0.1350 and save changes, the row will get updated but the value is saved as 0.1300 so it has lost the 0.005. I know the database can hold that precision as it currently does for some manually inserted data, and EF retrieves that without issue.

What on earth do I need to do to get EF to update my row/maintain precision. Help much appreciated, I might go cry.

Lee
  • 236
  • 1
  • 2
  • 10
  • Have you had a look at your model configuration to see what precision is set there? http://stackoverflow.com/questions/3504660/decimal-precision-and-scale-in-ef-code-first – Paddy Sep 17 '14 at 13:40
  • 1
    You are correct Paddy, I left this issue for a few hours and after posting the question found the answer I was looking for on google, setting the precision was indeed the fix, I'm guessing EF default is 2. Thank you – Lee Sep 17 '14 at 13:43

1 Answers1

4

So I found the answer to my own question after having left the issue for a while. It would seem EF default precision for decimals is 2, I can override this myself and set it to 4 as I want. I stole the code from this previously answered question:

Set decimal(16, 3) for a column in Code First Approach in EF4.3

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<MyClass>().Property(x => x.SnachCount).HasPrecision(16, 3);
    modelBuilder.Entity<MyClass>().Property(x => x.MinimumStock).HasPrecision(16, 3);
    modelBuilder.Entity<MyClass>().Property(x => x.MaximumStock).HasPrecision(16, 3);
}
Community
  • 1
  • 1
Lee
  • 236
  • 1
  • 2
  • 10
  • Won't let me do it for two days unfortunately, if you want to post this answer I'll happily accept it so the question can be resolved quicker :) – Lee Sep 17 '14 at 13:49
  • No need for dupe answer. Yours is the correct one, don't think the wait is a big issue. – Paddy Sep 17 '14 at 13:53