reorganization of database layer
This commit is contained in:
53
UserService.DatabaseLayer/Repository/BaseRepository.cs
Normal file
53
UserService.DatabaseLayer/Repository/BaseRepository.cs
Normal file
@ -0,0 +1,53 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq.Expressions;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using UserService.DatabaseLayer.DataModels;
|
||||
|
||||
namespace UserService.DatabaseLayer.Repository
|
||||
{
|
||||
public class BaseRepository<T> where T : class
|
||||
{
|
||||
private readonly Func<UserServiceDbContext, DbSet<T>> _context;
|
||||
|
||||
protected BaseRepository(Func<UserServiceDbContext, DbSet<T>> context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<T>> GetAllAsync(CancellationToken token = default)
|
||||
{
|
||||
await using var db = new UserServiceDbContext();
|
||||
return await _context(db).ToListAsync(token);
|
||||
}
|
||||
|
||||
public async Task<T?> GetAsync(Expression<Func<T, bool>> predicate, CancellationToken token = default)
|
||||
{
|
||||
await using var db = new UserServiceDbContext();
|
||||
return await _context(db).FirstOrDefaultAsync(predicate, token);
|
||||
}
|
||||
|
||||
public async Task AddAsync(T entity, CancellationToken token = default)
|
||||
{
|
||||
await using var db = new UserServiceDbContext();
|
||||
await _context(db).AddAsync(@entity, token);
|
||||
await db.SaveChangesAsync(token);
|
||||
}
|
||||
|
||||
public async Task UpdateAsync(T entity, CancellationToken token = default)
|
||||
{
|
||||
await using var db = new UserServiceDbContext();
|
||||
_context(db).Update(entity);
|
||||
await db.SaveChangesAsync(token);
|
||||
}
|
||||
|
||||
public async Task DeleteAsync(T entity, CancellationToken token = default)
|
||||
{
|
||||
await using var db = new UserServiceDbContext();
|
||||
_context(db).Remove(entity);
|
||||
await db.SaveChangesAsync(token);
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user