Search code examples
design-patternsrepository-patternbusiness-logic

Should the repository or the business layer update all tables?


In my project, I have a Customers table, with 3 foreign keys to the Addresses table. One for MainAddress, one for BillingAddress and one for ShippingAddress.

I am using a unit of work and repository pattern with a CustomerRepository and AddressRepository.

Occasionally I will need to work with the addresses on their own, but most of the time they will be part of the Customers domain object.

My question is a best practices design question. Should the business logic layer be responsible for calling both the CustomerRepository and AddressRepository to add/update, or should the CustomerRepository be smart enough to add/update addresses so that the BLL needs only call "AddCustomer" or "EditCustomer" and all the addresses tables are automatically added/updated?


Solution

  • I would let the CustomerRepository also handle the update of the Addresses. I assume you are using an object model where a customer object has a generic collection of addresses using a "has a" relationship (i.e. a customer has addresses). If you are using an ORM under the hood of your repository it will handle the update of this object and its relationships anyway. I see no benefit to have each repository handle the individual objects of this relationship or with your business logic needing to handle updates of this relationship. I would use the AddressRepository only when working directly with addresses. That is my advice for this example of a simple "has a" relationship. There will be times with more complex relationships where you will want to have the business logic handle this for you instead of the repository. An example might be when the objects are distributed across different data stores.