Repository — abstract data access.
Interface:
1public interface IRepository<T> where T : class2{3 Task<T> GetByIdAsync(int id);4 Task<IEnumerable<T>> GetAllAsync();5 Task AddAsync(T entity);6 Task UpdateAsync(T entity);7 Task DeleteAsync(int id);8}
Implementation:
1public class Repository<T> : IRepository<T> where T : class2{3 protected readonly DbContext _context;4 protected readonly DbSet<T> _dbSet;56 public Repository(DbContext context)7 {8 _context = context;9 _dbSet = context.Set<T>();10 }1112 public async Task<T> GetByIdAsync(int id) =>13 await _dbSet.FindAsync(id);14}
Key: Repository for data access abstraction.