I'm developing an application with Entity Framework, with several repositories.
Each repository encapsulates SaveChanges()
of DbContext.
When a business layer operation uses multiple repositories, and data changes, I need to call SaveChanges()
only once.
Obviously, I can do this in any repository, but I find it odd to have to call one at random. What is the recommendation in this situation?
EDITED
Repositories are only in interfaces for now, there is no implementation, there is one
public interface IUserRepository
{
User getByID(string ID);
User getByIDWithActiveGlossaries(string ID);
IEnumerable<User> getAll();
bool Save();
}
And there are other repositories, all implementing Save()
. Save is in a base interface, I put it together here for simplicity. Save will call SaveChanges()
of DbContext
.
PS: I evaluated the use of UnitOfWork
, but discarded, seeing no need. This is why, alias, I call SaveChanges()
at the end of a full operation, which may involve several changes.
FINAL EDITION
I had discarded the use of Unit of Work because there was no need for a mechanism to group the operations, since SaveChanges()
is already "all or nothing" (all operations are successful or all are reversed).
However, thanks to the answers from Hokos and Dherik, I realized that Unit of Work
does not only have this functionality, but also allows you to group the Save()
operation.