How do I handle table relationships with the repository pattern?
I'm implementing the repository pattern as part of an ASP.NET MVC site. Most examples I've seen of repositories are fairly simple. For example here's a typical abstract repository interface.
public interface IRepository<TEntity>
{
IQueryable<TEntity> All();
TEntity FindBy(int id);
TEntity FindBy(Exp开发者_JAVA技巧ression<Func<TEntity, bool>> expression);
IQueryable<TEntity> FilterBy(Expression<Func<TEntity, bool>> expression);
bool Add(TEntity entity);
bool Update(TEntity entity);
bool Delete(TEntity entity):
}
It's clear to me how you would use a repository like this to add, update, delete, or get entities of a single type. But how do you handle creating and manipulating one-to-many or many-to-many relationships between different types?
Say you have an Item
type where each item is assigned to a Category
. How would you make this assignment through the repository? Should this be up to the Update(Category c)
and/or Update(Item i)
methods to figure out what relationships need to be made to or from the element being updated? Or should there be an explicit AssignCategoryToItem(Item i, Category c)
method?
If it makes any difference I'm using Fluent NHibernate to implement my concrete repositories.
How does your app handle assigning a category to an item?
Does it:
- Allows the user to view the item then assign it a category
- Allows the user to view the category then add items to it
Let your app dictate which method you pick.
This brings up the idea of having a Business Logic/Services
layer and dealing with aggregate roots. In my applications, I always have a services
layer where all the business logic is at. I found that doing this has made my application easier to understand and maintain/refactor. (Note: I also use generic repositories and put the complex repository look ups in separate functions in the proper service class)
In your services
layer, you'll have a function called AssignCategoryToItem
which would then take the category (the aggregate root) and you would then add the item to that category
and save the changes - although I would prefer passing in the IDs
of the category and pulling it from the database before updating.
Once you have defined your aggregate roots you should create very specific repository interfaces (such as IProductRepository) for these, and have your service layer consume them.
Such as...
public interface IProductRepository
{
IList<Product> GetProductsInCategory(Category c);
Product GetProductBy(int id);
IList<Category> GetActiveProductCategories();
}
Then in your concrete implementation of IProductRepository you would consume the generic repository and query your related entities and join them as required.
精彩评论