Files
PersonaCasa/back/Infra/BaseRepository.cs
Alejandro Sarmiento b672887299 Primera subida
2024-04-06 03:32:16 +02:00

96 lines
3.6 KiB
C#

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<T> : IAsyncRepository<T> where T : BaseEntity
{
protected readonly Application_Db_Context context;
private readonly IDbContextFactory<Application_Db_Context> _dbContextFactory;
public BaseRepository(IDbContextFactory<Application_Db_Context> dbContextFactory, Application_Db_Context _context)
{
context = _context;
_dbContextFactory = dbContextFactory;
}
public virtual async Task<IReadOnlyList<T>> GetAllAsync()
{
using (var context = _dbContextFactory.CreateDbContext())
{
return await context.Set<T>().ToListAsync();
}
}
public virtual async Task<IReadOnlyList<T>> GetAsync(Expression<Func<T, bool>> predicate)
{
return await context.Set<T>().Where(predicate).ToListAsync();
}
public virtual async Task<IReadOnlyList<T>> GetAsync(Expression<Func<T, bool>>? predicate = null,
Func<IQueryable<T>, IOrderedQueryable<T>>? orderBy = null,
string includeString = null,
bool disableTracking = true)
{
IQueryable<T> query = context.Set<T>();
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<IReadOnlyList<T>> GetAsync(Expression<Func<T, bool>>? predicate = null,
Func<IQueryable<T>, IOrderedQueryable<T>>? orderBy = null,
List<Expression<Func<T, object>>>? includes = null,
bool disableTracking = true)
{
IQueryable<T> query = context.Set<T>();
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<T> GetByIdAsync(int id)
{
return await context.Set<T>().FindAsync(id);
}
public virtual async Task<T> AddAsync(T entity)
{
context.Set<T>().Add(entity);
await context.SaveChangesAsync();
return entity;
}
public virtual async Task<T> UpdateAsync(T entity)
{
context.Set<T>().Attach(entity);
context.Entry(entity).State = EntityState.Modified;
await context.SaveChangesAsync();
return entity;
}
public virtual async Task DeleteAsync(T entity)
{
context.Set<T>().Remove(entity);
await context.SaveChangesAsync();
}
}
}