I am using Entity Framework 6.x, using the Code First approach in an MVC 5 application. In this particular situation, my model (among other things) contains two properties named Latitude and Longitude:
[Required, Range(-90, +90)] public decimal Latitude { get; set; } [Required, Range(-180, +180)] public decimal Longitude { get; set; }
And when I migrated, I got something like this
CreateTable("ResProperty"), c => new { : Latitude = c.Decimal(nullable: false, precision: 10, scale: 8), Longitude = c.Decimal(nullable: false, precision: 11, scale: 8), : }) ... other stuff
therefore, both latitude and longitude have 8 decimal digits. The first has 2 integers (maximum 90), and the second has 3 integers (max. 180).
After running the Update-Database command, my table columns are displayed as:
Latitude decimal(10,8) Longitude decimal(11,8)
which seems good to me. Now, in my opinion, I have a map code and Javascript that allows the user to move the marker. It works well. When the marker moves, the Latitude and Longitude fields are filled with an updated value, which (Javascript) has more than 12 decimal digits. It doesn’t matter for AFAIK, because my scale is 8 decimal places.
After clicking the submit button and calling the Create or Edit POST method, I examine the model instance, and I confirmed that the actual values passed in the model to the controller are correct, they have more than decimal digits (this is the place of the Javascript code). Therefore, the value is correct.
Now ... the problem is that after db.SaveChanges () is executed, the database is updated - and I confirmed that the actual write / update occurred, but somehow inside EF ignores my actual values and writes truncated latitude / longitude rounded up to ONLY TWO decimal digits, so my Latitude shows in the database as 09.500000000 all other decimal digits are reset, because rounding seems to have taken place.
Why does he round it if I give the correct scale and accuracy, and the column has the correct scale and accuracy? Why does SaveChanges change my values?
I found this post ( http://weiding331.blogspot.com/2014/01/entity-framework-decimal-value.html ) which is the same problem, but I do not know how I can fix it (if it is) , because I already performed several migrations and adding data after the table was "migrated".
Summarizing
- Model data type correct (decimal)
- Database migration code has correct accuracy / scale (lat 10/8 lon 11/8)
- SQL database columns have the correct precision / scale (lat 10/8, long 11/8)
- Values transferred to the model have at least 8 decimal digits for latitude and longitude.
- the actual recording / updating of the value occurs in the database without errors, but ...
- The values recorded in the database for these two columns are truncated to TWO decimal digits and show the other least significant decimal digits as zero (0)