How do you implement Repository pattern with Entity Framework?
Here's a basic example:
// Entity
public class Product
public int Id { get; set; }
public string Name { get; set; }
// Generic Repository Interface
public interface IRepository<T> where T : class
Task<IEnumerable<T>> GetAllAsync();
Task<T> GetByIdAsync(int id);
Task AddAsync(T entity);
void Update(T entity);
void Delete(T entity);
Task SaveAsync();
// EF Core implementation
public class Repository<T> : IRepository<T> where T : class
private readonly DbContext _context;
private readonly DbSet<T> _dbSet;
public Repository(DbContext context)
_context = context;
_dbSet = context.Set<T>();
public async Task<IEnumerable<T>> GetAllAsync() => await
_dbSet.ToListAsync();
public async Task<T> GetByIdAsync(int id) => await
_dbSet.FindAsync(id);
public async Task AddAsync(T entity) => await
_dbSet.AddAsync(entity);
public void Update(T entity) => _dbSet.Update(entity);
public void Delete(T entity) => _dbSet.Remove(entity);
public async Task SaveAsync() => await
_context.SaveChangesAsync();