Having the repository pattern provide these benefits:
- Increase Testability: Repository systems are good for testing. One reason is you can use dependency injection. You create an interface for the repository and you reference the interface for it. After that, you can make a fake object such as moq.
- Easily change the data source: Just an example, in one instance, you need to retrieve data from the database, in other case, you need to retrieve something from a third party API or from other source of database. Regardless, the idea behind the repository pattern is that whatever sits behind, it doesn’t matter as long as the API provides works for the layer of the application calling into it.
This is the simple interface that I created:
public interface IRepository { IQueryable<TEntity> GetAll<TEntity>() where TEntity : class; TEntity GetById<TEntity>(int id) where TEntity : class; int Create<TEntity>(TEntity entity) where TEntity : class; void Update<TEntity>(TEntity entity) where TEntity : class; int Delete<TEntity>(int id) where TEntity : class; }
This is the implementation of the IRepostory.
public class Repository : IRepository { public IQueryable<TEntity> GetAll<TEntity>() where TEntity : class { try { return _context.Set<TEntity>().AsNoTracking(); } catch (Exception e) { _logger.AddLog(LogLevel.Error, $"Retrieve Error: { typeof(TEntity)}", e); throw; } } public TEntity GetById<TEntity>(int id) where TEntity : class { try { return _context.Set<TEntity>().Find(id); } catch (Exception e) { Console.WriteLine(e); throw; } } public int Create<TEntity>(TEntity entity) where TEntity : class { try { _context.Set<TEntity>().Add(entity); return _context.SaveChanges(); } catch (Exception e) { _logger.AddLog(LogLevel.Error, $"Create Error: { typeof(TEntity)}", e); throw; } } public void Update<TEntity>(TEntity entity) where TEntity : class { try { _context.Set<TEntity>().AddOrUpdate(entity); } catch (Exception e) { _logger.AddLog(LogLevel.Error, $"Update Error: { typeof(TEntity)}", e); throw; } } public int Delete<TEntity>(int id) where TEntity : class { try { var item = GetById<TEntity>(id); _context.Set<TEntity>().Remove(item); return _context.SaveChanges(); } catch (Exception e) { _logger.AddLog(LogLevel.Error, $"Delete Error: { typeof(TEntity)}", e); throw; } } }