58 lines
2.0 KiB
C#
58 lines
2.0 KiB
C#
#nullable enable
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
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 : Node
|
|
{
|
|
protected readonly Func<UserServiceDbContext, DbSet<T>> Context;
|
|
|
|
protected BaseRepository(Func<UserServiceDbContext, DbSet<T>> context)
|
|
{
|
|
Context = context;
|
|
}
|
|
|
|
public virtual async Task<IReadOnlyList<T>> GetAllAsync(Expression<Func<T, bool>>? predicate = null, CancellationToken token = default)
|
|
{
|
|
await using var db = new UserServiceDbContext();
|
|
|
|
IQueryable<T> queryable = Context(db).Include(x => x.Parent);
|
|
if(queryable != null) queryable = queryable.Where(predicate);
|
|
return await queryable.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);
|
|
}
|
|
}
|
|
} |