source: ChapterX.Infrastructure/Repositories/GenericRepository.cs@ acf690c

main
Last change on this file since acf690c was acf690c, checked in by kikisrbinoska <srbinoskakristina07@…>, 4 months ago

Added fixes for the login,stories management and reading lists

  • Property mode set to 100644
File size: 1.6 KB
Line 
1using ChapterX.Domain.Repositories;
2using ChapterX.Domain.Shared;
3using ChapterX.Infrastructure.Data.DataContext;
4using Microsoft.EntityFrameworkCore;
5
6namespace 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 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}
Note: See TracBrowser for help on using the repository browser.