-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRepository.cs
More file actions
59 lines (50 loc) · 1.86 KB
/
Repository.cs
File metadata and controls
59 lines (50 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
using Microsoft.EntityFrameworkCore;
using QuickFinder.Data;
namespace QuickFinder;
public interface IRepository<T, U>
where T : class
{
Task<T?> GetByIdAsync(U id, CancellationToken cancellationToken = default);
Task<List<T>> GetAllAsync(CancellationToken cancellationToken = default);
Task AddAsync(T entity, CancellationToken cancellationToken = default);
Task UpdateAsync(T entity, CancellationToken cancellationToken = default);
Task DeleteAsync(U id, CancellationToken cancellationToken = default);
}
public class Repository<T, U> : IRepository<T, U>
where T : class
{
private readonly ApplicationDbContext _dbContext;
private readonly DbSet<T> _dbSet;
public Repository(ApplicationDbContext db)
{
_dbContext = db ?? throw new ArgumentNullException(nameof(db));
_dbSet = _dbContext.Set<T>();
}
public async Task<T?> GetByIdAsync(U id, CancellationToken cancellationToken = default)
{
return await _dbSet.FindAsync([id], cancellationToken);
}
public async Task<List<T>> GetAllAsync(CancellationToken cancellationToken = default)
{
return await _dbSet.ToListAsync(cancellationToken);
}
public async Task AddAsync(T entity, CancellationToken cancellationToken = default)
{
_dbSet.Add(entity);
await _dbContext.SaveChangesAsync(cancellationToken);
}
public async Task UpdateAsync(T entity, CancellationToken cancellationToken = default)
{
_dbSet.Update(entity);
await _dbContext.SaveChangesAsync(cancellationToken);
}
public async Task DeleteAsync(U id, CancellationToken cancellationToken = default)
{
var entity = await _dbSet.FindAsync([id], cancellationToken);
if (entity != null)
{
_dbSet.Remove(entity);
await _dbContext.SaveChangesAsync(cancellationToken);
}
}
}