EFCore - When to save changes
I have an application that uses EFCore.
In this application, I have a method that gets some values from the database, and may or may not change them based on some conditions.
How should I handle the saving of changes in this scenario?
I've thought of a few solutions:
- Meticulously try to only call SaveChanges if a values was changed (for example by having a local change boolean)
- Simply always call SaveChanges at the end of the function
- A hybrid approach, call DbContext.ChangeTracker.HasChanges() and only call SaveChanges if this returns true
What would be the best approach of these? (alternate approaches are also welcome)
3 Replies
Save when you need to actually save something, IMHO
That said, the change tracker should be smart enough to just do nothing, if no changes have been made
Which would then be better, option 2 or 3?
I've tried looking into the save changes method, but could not actually find a call to
HasChanges
, which made me worried that it might do a lot of preparation or something before actually checking if anything needs to be done...just call savechanges at the end until that proves to negatively impact performance (probably won't)