Skip to content

Instantly share code, notes, and snippets.

@filipw
Last active October 30, 2023 21:14
Show Gist options
  • Save filipw/4502859 to your computer and use it in GitHub Desktop.
Save filipw/4502859 to your computer and use it in GitHub Desktop.
Generic EF repository
public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : class, IId
{
internal DbContext Context;
internal DbSet<TEntity> DbSet;
public ICache Cache { get; set; }
public GenericRepository(DbContext context)
{
Context = context;
DbSet = context.Set<TEntity>();
}
public virtual IEnumerable<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) query = AddIncludes(query, includes);
if (orderBy != null) return orderBy(query).ToList();
else return query.ToList();
}
public virtual TEntity GetById(Guid id, params Expression<Func<TEntity, object>>[] includes)
{
var query = AddIncludes(DbSet, includes);
return query.SingleOrDefault(i => i.Id == id);
}
public virtual void Insert(TEntity entity)
{
DbSet.Add(entity);
}
public virtual void Delete(object id)
{
TEntity entityToDelete = DbSet.Find(id);
Delete(entityToDelete);
}
public virtual void Delete(TEntity entityToDelete)
{
if (Context.Entry(entityToDelete).State == EntityState.Detached) DbSet.Attach(entityToDelete);
DbSet.Remove(entityToDelete);
}
public virtual void Update(TEntity entityToUpdate)
{
DbSet.Attach(entityToUpdate);
Context.Entry(entityToUpdate).State = EntityState.Modified;
}
private IQueryable<TEntity> AddIncludes(IQueryable<TEntity> query, IEnumerable<Expression<Func<TEntity, object>>> includes)
{
if (includes != null) query = includes.Aggregate(query, (current, include) => current.Include(include));
return query;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment