EF Core Loses Decimal Precision After Save
I'm building a financial system for budgeting. All my money values in SQL server are stored as numeric(18, 2), which is correctly understood by EF Core. However, if I make a calculation that results in numbers beyond 2 decimal places and save it, EF Core does not automatically truncate the decimal value that was saved on the entity object.
In the screenshot, I calculated a new value for "AmountPerMonth" and saved it via SaveChanges. After the save, the "Budget" entity object still has numbers beyond 2 decimal places. If I purge it and completely reload from DB, it loads only 2 decimal places, because obviously in the database it only saves 2. But I need it do truncate it after save, since I am trying to be efficient and automatically caching the value after save.
10 Replies
how is your model defined/configured?
It's a database first approach, but lemme check
there will be EF configuration for it either way
i'm not sure if EF is even intended to do what you're expecting it to do, but the first thing i'd check is make sure that it actually knows the column has a specific precision and scale
I think it does?
are the amounts in your model
decimal
or another floating point type?decimal
I have a Mapper class where I can override it if I have to, so it wouuldn't be too big of a deal to do it manually. Just wanted to check in case there was something already out there that does it
I have to step away for a bit, kids need help
actually, I have to head out, I'm super tired. Thanks for your help, maybe tomorrow I'll find something
https://stackoverflow.com/questions/3504660/decimal-precision-and-scale-in-ef-code-first#7769162
This might have what you're looking for?
I'm finally settling down from a busy morning. I'll take a look at this, thank you!
Hmnm, I'm not sure that will work for me. Mine is database-first. I'm not sure how to implement this change
I assume it is still required if you want EF to be aware of precision constraints when tracking changes
but I'm mostly guessing, never had to deal with precision myself
Appreciate the help, thanks 🙂