Search code examples
c#asp.net-coresingle-responsibility-principle

Single Responsibility Principle and Many methods in Repository


I am trying to understand the Single-Responsibility Principle (SRP). It says a class should have only one responsibility and reason to change. This is a typical Repository below. Does that mean, each item should be its own class? Currently Insert, Delete, Search, are all in 1 class? If that's the case, why don't people separate all the items into multiple classes?

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);
    }
}

Solution

  • question: what are the responsibilities of this repository class?

    answer : to execute operations against a database (CRUD)

    further reading: http://pragmaticcraftsman.com/2006/07/single-responsibility-principle