C# public class Repository<T> : IRepository<T> where T : class
{
protected readonly DbContext _context;
protected readonly DbSet<T> _dbSet;
protected readonly ILogger _logger;
public Repository(DbContext context, ILogger logger)
{
_context = context;
_dbSet = context.Set<T>();
_logger = logger;
}
public virtual async Task<T?> GetByIdAsync(int id)
{
var data = await _dbSet.FindAsync(id);
if (data == null) { return null; }
else { return data; }
}
public virtual async Task<IEnumerable<T>> GetAllAsync()
{
return await _dbSet.ToListAsync();
}
public virtual async Task AddAsync(IEnumerable<T> entities)
{
await _dbSet.AddRangeAsync(entities);
await _context.SaveChangesAsync();
}
public virtual async Task UpdateAsync(IEnumerable<T> entities)
{
_dbSet.UpdateRange(entities);
await _context.SaveChangesAsync();
}
}
public class DepartmentRepository : Repository<Department>, IDepartmentRepository
{
private readonly DbContext _context;
public DepartmentRepository(DbContext context, ILogger logger) : base(context, logger)
{
_context = context;
}
public override async Task<IEnumerable<Department>> GetAllAsync()
{
try
{
var result = await _dbSet.Where(x => x.IsActive == true).ToListAsync();
return result.AsEnumerable();
}
catch (Exception ex)
{
_logger.LogError((ex), "{Repo} GetAllAsync ", typeof(DepartmentRepository));
return null;
}
}
}
Program.cs
builder.Services.AddScoped<IDepartmentRepository, DepartmentRepository>();