using Microsoft.EntityFrameworkCore; using System.Linq.Expressions; using System.Linq; using back.Entities; using back.Application.Contracts.Persistence; using Microsoft.EntityFrameworkCore.Internal; namespace back.Infra { public class BaseRepository : IAsyncRepository where T : BaseEntity { protected readonly Application_Db_Context context; private readonly IDbContextFactory _dbContextFactory; public BaseRepository(IDbContextFactory dbContextFactory, Application_Db_Context _context) { context = _context; _dbContextFactory = dbContextFactory; } public virtual async Task> GetAllAsync() { using (var context = _dbContextFactory.CreateDbContext()) { return await context.Set().ToListAsync(); } } public virtual async Task> GetAsync(Expression> predicate) { return await context.Set().Where(predicate).ToListAsync(); } public virtual async Task> GetAsync(Expression>? predicate = null, Func, IOrderedQueryable>? orderBy = null, string includeString = null, bool disableTracking = true) { IQueryable query = context.Set(); if (disableTracking) query = query.AsNoTracking(); if (!string.IsNullOrWhiteSpace(includeString)) query = query.Include(includeString); if (predicate != null) query = query.Where(predicate); if (orderBy != null) return await orderBy(query).ToListAsync(); return await query.ToListAsync(); } public virtual async Task> GetAsync(Expression>? predicate = null, Func, IOrderedQueryable>? orderBy = null, List>>? includes = null, bool disableTracking = true) { IQueryable query = context.Set(); if (disableTracking) query = query.AsNoTracking(); if (includes != null) query = includes.Aggregate(query, (current, include) => current.Include(include)); if (predicate != null) query = query.Where(predicate); if (orderBy != null) return await orderBy(query).ToListAsync(); return await query.ToListAsync(); } public virtual async Task GetByIdAsync(int id) { return await context.Set().FindAsync(id); } public virtual async Task AddAsync(T entity) { context.Set().Add(entity); await context.SaveChangesAsync(); return entity; } public virtual async Task UpdateAsync(T entity) { context.Set().Attach(entity); context.Entry(entity).State = EntityState.Modified; await context.SaveChangesAsync(); return entity; } public virtual async Task DeleteAsync(T entity) { context.Set().Remove(entity); await context.SaveChangesAsync(); } } }