I've been doing a lot of reading about repository pattern (Linq2SQL or EF). I've seen some repositories with some specific queries, such as FindUserByName
where I would开发者_如何学Python pass a where expression to the repository.
On the other hand, I've seen some repositories with just "Save, Update and GetAll" and GetAll
return a IQueryable. And, this IQueryable is filtered in the service layer.
So, in your opinion, is it good to pass specific queries to repository or just have it simpler as possible and let all of the filters occurs in service?
Thanks!
My advice is to create a GenericRepository<T>
, which has the core basic methods (Find
, Save
, Delete
, etc).
Example:
public abstract class GenericRepository<T> : IRepository<T> where T : class
{
public T FindSingle(Expression<Func<T,bool>> predicate) { .. };
public IQueryable<T> Find() { .. };
public void Delete(T entity) { .. };
}
Then create specific repositories that inherit from the generic one, to create specialized methods.
Example:
public class EmployeeRepository : GenericRepository<Employee>, IRepository<Employee>
{
public Employee FindByLastName(string lastName)
{
return FindSingle(emp => emp.LastName == lastName);
}
public ICollection<Employee> FindAllManagers()
{
return Find().Where(emp => emp.Type == "Manager").ToList();
}
// other methods...
}
This means you're not duplicating common code across your repositories.
And yes, the other alternative is to have services which work off the GenericRepository<T>
. Which means the services are (essentially) a specialized repository.
So it's just a matter of preference if you want a service layer or specialized repositories.
精彩评论