I am new to learning Repository Pattern. I am developing a site in MVC 4 (I'm new to it as well).
The way I am using Repository pattern as follows:
I created
IRepository<T>
interface as follows:public interface IRepository<T> { void Insert(T entity); void Delete(T entity); IQueryable<T> SearchFor(Expression<Func<T, bool>> predicate); IQueryable<T> GetAll(); T GetById(int id); }
Then I created a base class which implements the above interface as follows:
public class BaseRepository<TEntity> : IRepository<TEntity> where TEntity : class { private readonly DbContext _dbContext; public BaseRepository(DbContext dbContext) { _dbContext = dbContext; } public void Insert(TEntity entity) { _dbContext.Set<TEntity>().Add(entity); _dbContext.SaveChanges(); } public void Delete(TEntity entity) { _dbContext.Set<TEntity>().Remove(entity); _dbContext.SaveChanges(); } public IQueryable<TEntity> SearchFor(Expression<Func<TEntity, bool>> predicate) { return _dbContext.Set<TEntity>().Where(predicate); } public IQueryable<TEntity> GetAll() { return _dbContext.Set<TEntity>(); } public TEntity GetById(int id) { return _dbContext.Set<TEntity>().Find(id); } }
Now for each repository I want to create, I create another interface which contains methods specific to that class. E.g if I want to create a
CustomersRepository
, I create an interfaceICustomersRepository
as follows:public interface ICustomersRepository: IRepository<Customer> { IEnumerable<Customer> GetRecentCustomers(); Customer GetByName(string customerName); }
Now I create
CustomersRepository
class, derive it fromBaseRepository
and implementICustomersRepository
. as follows:public class CustomersRepository : BaseRepository<Customer>, ICustomersRepository { private readonly DbContext _dbContext; public CustomersRepository(DbContext dbContext) : base(dbContext) { _dbContext = dbContext; } public IEnumerable<Customer> GetRecentCustomers() { // implementation } public Customer GetByName(string customerName) { // } }
Now to create another Repository, I will have to create an interface for it, then create that repository class which will implement BaseRepository<TEntity>
class, implement the specific repository interface.
Issues:
- This is not the proper way. But I use it as I get a
BaseRepository<TEntity>
which gives me many functions implemented. - I have to pass
DbContext
for each repository class. - not satisfied
Can you please guide me have this code corrected? I will be using the same approach in almost all of my future projects where I use an ORM.
IRepository<T>
and have onlyabstract BaseRepository<T>
. \$\endgroup\$