mardi 10 juillet 2018

Repository Pattern Dilemma: Redundant Queries vs. Database Round Trips

This is the situation:

Say I have an application in which two entity types exist:

  • Company
  • Person

Moreover, Person has a reference to Company via Person.employer, which denotes the company a person is employed at.

In my application I am using repositories to separate the database operations from my business-model related services: I have a PersonRepository to retrieve Person entities and a CompanyRepository to retrieve Company entities. So far so good.

This is the dilemma:

Now if I make a call to PersonRepository.findOne(id) to fetch a Person entity, I also need to have a fully resolved Company included inline via the Person.employer property – and this is where I am facing the dilemma of having two implementation options that are both suboptimal:

Option A) Redundant queries throughout my repositories but less database round trips:

Within the PersonRepository I can build a query which selects the user and also selects the company in a single query – however, the select expression for the company is difficult and includes some joins in order to assemble the company correctly. The CompanyRepository already contains this logic to select the company and rewriting it in the UserRepository is redundant. Hence, ideally I only want the CompanyRepository to take care of the company selection logic in order to avoid having to code the same query expression redundantly in two repositories.

Option B): Separation of concerns without query-code redundancy but at the price of additional db roundtrips and repo-dependencies:

Within the PersonRepository I could reference the CompanyRepository to take care of fetching the Company object and then I would add this entity to the Person.employer property in the PersonRepository. This way, I kept the logic to query the company encapsulated inside the CompanyRepository by which a clean separation of concerns is achieved. The downside of this is that I make additional round trips to the database as two separate queries are executed by two repositories.

So generally speaking, what is the preferred way to deal with this dilemma?

Also, what is the preferred way to handle this situation in ASP.NET Core and EF Core?

Aucun commentaire:

Enregistrer un commentaire