'Should I call SaveChanges() in my repository or what should I do in case I absolutely have to call it?

I've seen many examples where other developers suggest to not call SaveChanges() or SaveChangesAsync() in every function of a repository class which modifies something in the database because it would be much slower compared to only saving the changes at the very end. However, I keep running into problems with this approach because I often have to get the ID of a new entity in my repositories in order to do something else (like inserting into a different table). Therefore I do not see an alternative other than calling SaveChanges() in those cases. Does this mean that I should also be calling SaveChanges() in other repository functions for the sake of consistency, even if it is not required in all of them, or is there a better way to implement this? I do not want to constantly have to think if a function I am using already calls SaveChanges() or not, so I am not sure how to implement this in a way that is both efficient and also easy to work with for the developer. Right now I also have no way to manually call SaveChanges() from my service layer, so I really have no other option than calling it in the repositories.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source