Wednesday 4 June 2014

MVC4 Entity Framework and Decimal Precision

This just caught me out today so hopefully it will help someone else.

Stack Overflow answer here http://stackoverflow.com/questions/3504660/decimal-precision-and-scale-in-ef-code-first

If you have a database field with the spec decimal(18,5) the Entity Framework will still round the number to 2 decimal places by default, so if you enter a number e.g. 15.42700 it will be saved to your database as 15.42000, not very helpful eh. Anyway to fix it you need to override OnModelCreating in your DBContext Class

public class EFDbContext : DbContext { protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder) { modelBuilder.Entity().Property(object => object.property).HasPrecision(12, 10); base.OnModelCreating(modelBuilder); } }