C
C#•2mo ago
Camster

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
Jimmacle
Jimmacle•2mo ago
how is your model defined/configured?
Camster
Camster•2mo ago
It's a database first approach, but lemme check
Jimmacle
Jimmacle•2mo ago
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
Camster
Camster•2mo ago
I think it does?
Jimmacle
Jimmacle•2mo ago
are the amounts in your model decimal or another floating point type?
Camster
Camster•2mo ago
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
Camster
Camster•2mo ago
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
Keswiik
Keswiik•2mo ago
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
Camster
Camster•2mo ago
Appreciate the help, thanks 🙂