Skip to content

Instantly share code, notes, and snippets.

@mislavs
Created July 30, 2021 09:14
Show Gist options
  • Save mislavs/4d0e0328642e7efbbf655ef0b9963559 to your computer and use it in GitHub Desktop.
Save mislavs/4d0e0328642e7efbbf655ef0b9963559 to your computer and use it in GitHub Desktop.
Generic Repository implementation
using FileSystem.Data.Interfaces;
using FileSystem.Data.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Query;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace FileSystem.Data
{
/// <summary>
/// Generic repository for entities.
/// </summary>
/// <typeparam name="TEntity"></typeparam>
public class EntityRepository<TEntity> : IRepository<TEntity>
where TEntity : BaseEntity
{
private DatabaseContext DbContext { get; }
public EntityRepository(DatabaseContext context)
{
DbContext = context;
}
public async Task<IEnumerable<TEntity>> Get(bool disableTracking = true,
Expression<Func<TEntity, bool>>? filter = null,
Func<IQueryable<TEntity>, IIncludableQueryable<TEntity, object>>? include = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>>? orderBy = null,
int? maxResults = null)
{
IQueryable<TEntity> query = DbContext.Set<TEntity>();
if (disableTracking)
{
query.AsNoTracking();
}
if (filter != null)
{
query = query.Where(filter);
}
if (include != null)
{
query = include(query);
}
if (orderBy != null)
{
query = orderBy(query);
}
if (maxResults != null)
{
query = query.Take(maxResults.Value);
}
return await query.ToListAsync();
}
public async Task<TEntity?> GetById(Guid id)
{
return await DbContext.Set<TEntity>().FindAsync(id);
}
public void Insert(TEntity entity)
{
DbContext.Set<TEntity>().Add(entity);
}
public void Delete(TEntity entity)
{
DbContext.Set<TEntity>().Remove(entity);
}
public async Task Save()
{
await DbContext.SaveChangesAsync();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment