77 lines
2.1 KiB
C#
77 lines
2.1 KiB
C#
using System.Linq.Expressions;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace GamificationService.Database.GenericRepository;
|
|
|
|
public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : class
|
|
{
|
|
private readonly ApplicationContext _context;
|
|
private readonly DbSet<TEntity> _dbSet;
|
|
|
|
public GenericRepository(ApplicationContext context)
|
|
{
|
|
_context = context;
|
|
_dbSet = context.Set<TEntity>();
|
|
}
|
|
|
|
public virtual IQueryable<TEntity> Get(
|
|
Expression<Func<TEntity, bool>>? filter = null,
|
|
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>>? orderBy = null,
|
|
params Expression<Func<TEntity, object>>[] includes)
|
|
{
|
|
IQueryable<TEntity> query = _dbSet;
|
|
|
|
if (filter != null)
|
|
{
|
|
query = query.Where(filter);
|
|
}
|
|
|
|
if (includes != null)
|
|
{
|
|
foreach (var include in includes)
|
|
{
|
|
query = query.Include(include);
|
|
}
|
|
}
|
|
|
|
return orderBy != null ? orderBy(query) : query;
|
|
}
|
|
|
|
public virtual TEntity? GetById(object id) => _dbSet.Find(id);
|
|
|
|
public virtual async Task<TEntity?> GetByIdAsync(object id) =>
|
|
await _dbSet.FindAsync(id);
|
|
|
|
public virtual void Add(TEntity entity) => _dbSet.Add(entity);
|
|
|
|
public virtual void AddRange(IEnumerable<TEntity> entities) => _dbSet.AddRange(entities);
|
|
|
|
public virtual async Task AddAsync(TEntity entity) => await _dbSet.AddAsync(entity);
|
|
|
|
public virtual void Delete(object id)
|
|
{
|
|
var entity = _dbSet.Find(id);
|
|
if (entity == null)
|
|
{
|
|
throw new KeyNotFoundException($"Entity of type {typeof(TEntity).Name} with id '{id}' was not found.");
|
|
}
|
|
Delete(entity);
|
|
}
|
|
|
|
public virtual void DeleteRange(IEnumerable<TEntity> entities) => _dbSet.RemoveRange(entities);
|
|
|
|
public virtual void Delete(TEntity entity)
|
|
{
|
|
if (_context.Entry(entity).State == EntityState.Detached)
|
|
{
|
|
_dbSet.Attach(entity);
|
|
}
|
|
_dbSet.Remove(entity);
|
|
}
|
|
|
|
public virtual void Update(TEntity entity)
|
|
{
|
|
_dbSet.Update(entity);
|
|
}
|
|
}
|