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:
- Linq - I can return an IQueryable object from Repository for each type, then filter the query using linq expressions. I don't like this idea, because if I go this way, I don't see the reason behind Repository.
- Entity specific repository - Here I can build an entity specific on top of the generic repository. It will have methods such as Get(DateTime dateFrom, DateTime dateTo) etc. The drawback is that I'll have to create a repository class for each entity object. The good side is that it will be much easyer to persist/delete an object graph from database开发者_Go百科, because it knows entity's dependencies.
- You tell me please :)
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?
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.
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.
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.
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.
精彩评论