| 1 | using ChapterX.Domain.Repositories;
|
|---|
| 2 | using ChapterX.Domain.Shared;
|
|---|
| 3 | using ChapterX.Infrastructure.Data.DataContext;
|
|---|
| 4 | using Microsoft.EntityFrameworkCore;
|
|---|
| 5 |
|
|---|
| 6 | namespace ChapterX.Infrastructure.Repositories
|
|---|
| 7 | {
|
|---|
| 8 | // Generic repository for aggregate roots/entities implementing IEntity.
|
|---|
| 9 | public class GenericRepository<T> : IRepository<T> where T : class, IEntity
|
|---|
| 10 | {
|
|---|
| 11 | protected readonly ApplicationDbContext _context;
|
|---|
| 12 | protected readonly DbSet<T> _dbSet;
|
|---|
| 13 |
|
|---|
| 14 | public GenericRepository(ApplicationDbContext context)
|
|---|
| 15 | {
|
|---|
| 16 | _context = context;
|
|---|
| 17 | _dbSet = context.Set<T>();
|
|---|
| 18 | }
|
|---|
| 19 |
|
|---|
| 20 | public virtual async Task<T?> GetByIdAsync(int id, CancellationToken cancellationToken = default)
|
|---|
| 21 | => await _dbSet.FindAsync([id], cancellationToken);
|
|---|
| 22 |
|
|---|
| 23 | public virtual async Task<IEnumerable<T>> GetAllAsync(CancellationToken cancellationToken = default)
|
|---|
| 24 | => await _dbSet.ToListAsync(cancellationToken);
|
|---|
| 25 |
|
|---|
| 26 | public async Task AddAsync(T entity, CancellationToken cancellationToken = default)
|
|---|
| 27 | {
|
|---|
| 28 | await _dbSet.AddAsync(entity, cancellationToken);
|
|---|
| 29 | await _context.SaveChangesAsync(cancellationToken);
|
|---|
| 30 | }
|
|---|
| 31 |
|
|---|
| 32 | public async Task UpdateAsync(T entity, CancellationToken cancellationToken = default)
|
|---|
| 33 | {
|
|---|
| 34 | _dbSet.Update(entity);
|
|---|
| 35 | await _context.SaveChangesAsync(cancellationToken);
|
|---|
| 36 | }
|
|---|
| 37 |
|
|---|
| 38 | public async Task DeleteAsync(T entity, CancellationToken cancellationToken = default)
|
|---|
| 39 | {
|
|---|
| 40 | _dbSet.Remove(entity);
|
|---|
| 41 | await _context.SaveChangesAsync(cancellationToken);
|
|---|
| 42 | }
|
|---|
| 43 | }
|
|---|
| 44 | }
|
|---|