#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; using UserService.Infrastructure.DataModels; namespace UserService.DatabaseLayer.Repository { public class BaseRepository where T : Node { protected Func> Context { get; } protected BaseRepository(Func> context) { Context = context; } public virtual async Task> GetAllAsync(Expression>? predicate = null, CancellationToken token = default) { await using var db = new UserServiceDbContext(); return await Context(db).Include(x => x.Parent).WhereOrDefault(predicate).ToListAsync(token).ConfigureAwait(false); } public async Task GetAsync(Expression> predicate, CancellationToken token = default) { await using var db = new UserServiceDbContext(); return await Context(db).FirstOrDefaultAsync(predicate, token).ConfigureAwait(false); } public async Task AddAsync(T entity, CancellationToken token = default) { await using var db = new UserServiceDbContext(); await Context(db).AddAsync(@entity, token).ConfigureAwait(false); await db.SaveChangesAsync(token).ConfigureAwait(false); } public async Task UpdateAsync(T entity, CancellationToken token = default) { await using var db = new UserServiceDbContext(); Context(db).Update(entity); var items= await db.SaveChangesAsync(token).ConfigureAwait(false); return items > 0; } public async Task DeleteAsync(T entity, CancellationToken token = default) { await using var db = new UserServiceDbContext(); Context(db).Remove(entity); await db.SaveChangesAsync(token).ConfigureAwait(false); } } }