fjompen
fjompen

Reputation: 73

Service repository pattern, how to save multiple objects with many related entities

Relationship: Parent => Child => Grandchild

Got separate services and repos for the three entities. Client sends a parent containing a child and a grandchild to be created and saved in the database.

What's the "correct" approach here? Handling the creation of the different entities separate would mean I have to open 3 connections to the database for every parent, while handling it all in the same service/repo goes against the architecture.

Upvotes: 0

Views: 1956

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239290

This is where the concept of the unit of work pattern comes in. You have your repos and then you have a unit of work class that has properties for each of those repos. You inject your unit of work, and you can handle whatever you need to, transactionally.

This is so common with database access, in fact, that ORMs like Entity Framework do it for you. With Entity Framework, for example, the DbContext is your unit of work and each DbSet on it is a repository. You did not mention your database access method, but if you are using an ORM, that means you should not also implement the repository/unit of work patterns. It's a useless additional layer that simply adds additional maintenance and testing concerns with no benefit. If you're doing straight SQL with something like ADO.NET, then it's fine (and even recommended) to use the repository pattern, but you should combine it with the unit of work pattern, as well. You should start a transaction, utilize all your repositories, and then finally close the transaction. The unit of work is required to regulate all this.

Upvotes: 2

Related Questions