Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repository pattern and return types

I am using the repository pattern where I have one repository class per database table. I was wondering how you guys approach queries that only need to return a specific number of columns

For example say I have the following

Item Table (fictional table)

ItemId
Name
PurchaseDate
Description
Price

In my code I create an object with the fields above called Item.cs (currently not using an orm).

If I have multiple scenarios where I need to return

  1. ItemId
  2. A combination of PurchaseDate and Name
  3. ItemId and price

Which would be the best approach?

  1. Get all fields from the items table and return an Item object (1 repo query)
  2. Create three queries in Repo and return an Item object for each one
  3. Create three queries in Repo and return only what is needed?

Now imagine this scenario with a table with over 10 fields.

Personally, I like option one, but I'm not sure if there is a better way to go about this.

like image 418
chobo Avatar asked Feb 23 '12 18:02

chobo


People also ask

What repository pattern should return?

Your repositories should return domain objects and the client of the repository can decide if it needs to do the mapping. By mapping the domain objects to view models (or something else) inside a repository, you prevent the client of your repositories from getting access to the underlying domain object.

What type of pattern is repository?

The Repository pattern implements separation of concerns by abstracting the data persistence logic in your applications. Design patterns are used as a solution to recurring problems in your applications, and the Repository pattern is one of the most widely used design patterns.

Can we return DTO from repository?

Short answer: No. Long answer: repository is responsible for turning persisted data back to entities (models) and vice versa.

Should repositories return Dtos?

In most cases, it suffices to have a single entity-DTO conversion, which tends to happen in the business layer (BLL), which is one layer above the repository layer (DAL). In that sense, your repositories should not return a DTO.


1 Answers

I add methods to my repositories when I need them in contrast to generic repositories where you get a set of methods no matter if you need them or not.

Returning IQueryable is a leaky abstraction.

Take a look at Domain Driven Design (the book) and you'll get a good idea of how well designed repositories should look like.

I've also written a rant about generic repositories: http://blog.gauffin.org/2012/02/generic-repositories-a-silly-abstraction-layer/

like image 118
jgauffin Avatar answered Sep 19 '22 09:09

jgauffin