21. C#: Generic Repository (EF Core)
C#A universal data-access layer with async support.
public class Repository where T : class {
private readonly DbContext _context;
private readonly DbSet _dbSet;
public Repository(DbContext context) {
_context = context;
_dbSet = context.Set();
}
public async Task GetByIdAsync(int id) => await _dbSet.FindAsync(id);
}
When to use
Useful when many entities in the database require the same basic CRUD operations.
Common pitfalls
An overly generic repository makes it harder to add specific Include() queries or complex filters — sometimes it's better to split off inheriting repositories.