I’m using the Repository pattern, and have been for a long time, but there’s one thing I’ve never really found a good solution for. Often I need to access data that relates to multiple entities, and I can’t find what feels like a good solution for where to place that functionality. A few cases:
Assuming that in the system there are Users which have Tasks:
- I need to retrieve a list of the most recent task for each user as a pairing of User to Task, say as a
Dictionary<int, int> GetUsersRecentTask() - I need to generate a report of all Users and their Tasks for that month.
- I need to generate statistics on all the objects in the system.
Now normally I would just put it in say the Users repository, but it just doesn’t feel right.
I’ve also tried placing it in a higher level service, but it just doesn’t feel right to put data access there.
So where would I best place it.
Don’t consider the Repository pattern a dogma. It’s just a concept. So, the UsersRepository has GetUsersRecentTask wihle you have different repositories such as: ReportsRepository with GetUsersReport (which includes tasks) and StatisticsRepository with Get[Object]Stats .
While the Repository Pattern originally deals only with business objects, it’s still a good pattern if you need ‘lesser’ objects such as View Models or report data which are just data structures (no behavior). So it makes sense to ask the ReportsRepository for a certain report.
The only thing you have to be aware is that some repositories deal with business objects while others deal with DTOs .