Davita
Davita

Reputation: 9114

Generic repository. Need suggestion

I'm thinking which way to go and can't decide which one is better. Maybe you can give me the killer idea :)

My problem: I have a generic repository built on top of NHibernate. It's interface is very simple, such as Get(object id), Save, Delete etc. Sometime this interface works fine, but sometime it doesn't. For example, several entities in my project has a property named Code (but not all). I want to be able to get an entity not only by primary key, but also with this property. Another situation is when I need to filter some entities with dates, or provide other filtering criteria which are specific to individual entities. Currently I'm thinking of the following solutions:

Upvotes: 4

Views: 941

Answers (5)

gideon
gideon

Reputation: 19465

I use something that looks like this: Note, its for Entity Framework but the model/design could be used anywhere I guess.

public interface IRepository<T>
{
    T Save(T entity);
    void Delete(T entity);
    IQueryable<T> GetAll();
    T GetById(int id);
}

I picked it up from a number of questions that debate on using IQueryable, the whole advantage is, you can mock IRepository easily.

See this answer for full details.

Upvotes: 0

Jamie Ide
Jamie Ide

Reputation: 49261

I advocate using aggregate repositories rather than entity specific repositories. For example, if you have entities

Project
ProjectStatus
ProjectType

it makes sense to combine the data access to all these in a single repository instead of three separate ones.

Upvotes: 2

Bryan Watts
Bryan Watts

Reputation: 45445

I prefer entity-specific repositories, after putting a lot of effort into generic repositories.

This answer of mine (36 votes so far) elaborates on this stance and contains an approach you might be able to use:

Advantage of creating a generic repository vs. specific repository for each object?

Upvotes: 3

Joel Briggs
Joel Briggs

Reputation: 1839

Given that you already have a generic repository interface (I assume) I would go with the Entity specific repository, but implement it by extending your generic repository. This should make the code more discoverable and allow you to continue to adhere to your repository pattern. This will allow you to add methods for getting by Code and for getting by passing in a date range.

Upvotes: 3

Prasanna
Prasanna

Reputation: 3771

You can use named queries to get rows based on column that is not a key or do any kind of filtering using Hibernate Query Language (hql) which is pretty similar to sql statements.

This might help.

Upvotes: 0

Related Questions