Managing Relationships for an Entity

I’m having a few issues with figuring out what is responsible for managing relationships within entities.

Say I have an entity:

public class Customer : IEntity
{
    public string Name { get; set; }
    public List<Asset> Assets { get; set; }
}

And a repository called CustomerRepository. The customer repository can get a collection of customers from a persistent data source, and add and remove from said data source.

So far so good, I’m following the single responsibility principle. However, when I try to dot into the Assets for a customer:

CustomerRepository repo = new CustomerRepository();
var customer = repo.FindById(1);
var assets = customer.Assets;

I’ll find that the assets aren’t populated. The answer to this is to populate the assets somewhere… But where?!

I could do a more complicated get method in the Customer entity Assets property, with another repository for assets (AssetRepository), but this would violate the single responsibility principle. Not only is the Customer entity responsible for structuring data, but also for relationships.

I could populate the Assets directly in the repository, at the same time a customer entity is created, but again, this surely gives the repository more responsibility than it should have. It’s now creating and populating two sets of entities and assigning the Assets collection for the for a Customer, which gets even more inefficient and unwieldy when managing a collection of Customers (say in a Find() or GetActiveCustomers() methods). Not to mention if assets has another collection of entities within it, then the repository will be populating lots of different types of entity within entities within entities etc.

I feel as though I’ve missed something fundamental in the design, but no amount of googling is giving me the answer.

So in summary, what should be responsible for managing the relationships between entities, and populating the data for said entities.

I should also mention that I’m not using entity framework for this, so any pre-built implementation part of EF wouldn’t be suitable, but adapting a pattern that EF generates would be acceptable.


Source: oop

Leave a Reply