Created
October 10, 2019 21:29
-
-
Save Rudyzio/d1f4464d4105323425a54f945087e6a4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Repository<TEntity> : IRepository<TEntity> where TEntity : BaseEntity | |
{ | |
protected readonly DbContext _context; | |
public Repository(DbContext context) | |
{ | |
_context = context; | |
} | |
public void Add(TEntity entity) | |
{ | |
_context.Set<TEntity>().Add(entity); | |
} | |
public void AddRange(IEnumerable<TEntity> entities) | |
{ | |
_context.Set<TEntity>().AddRange(entities); | |
} | |
public bool Contains(ISpecification<TEntity> specification = null) | |
{ | |
return Count(specification) > 0 ? true : false; | |
} | |
public bool Contains(Expression<Func<TEntity, bool>> predicate) | |
{ | |
return Count(predicate) > 0 ? true : false; | |
} | |
public int Count(ISpecification<TEntity> specification = null) | |
{ | |
return ApplySpecification(specification).Count(); | |
} | |
public int Count(Expression<Func<TEntity, bool>> predicate) | |
{ | |
return _context.Set<TEntity>().Where(predicate).Count(); | |
} | |
public IEnumerable<TEntity> Find(ISpecification<TEntity> specification = null) | |
{ | |
return ApplySpecification(specification); | |
} | |
public TEntity FindById(int id) | |
{ | |
return _context.Set<TEntity>().Find(id); | |
} | |
public void Remove(TEntity entity) | |
{ | |
_context.Set<TEntity>().Remove(entity); | |
} | |
public void RemoveRange(IEnumerable<TEntity> entities) | |
{ | |
_context.Set<TEntity>().RemoveRange(entities); | |
} | |
public void Update(TEntity entity) | |
{ | |
_context.Set<TEntity>().Attach(entity); | |
_context.Entry(entity).State = EntityState.Modified; | |
} | |
private IQueryable<TEntity> ApplySpecification(ISpecification<TEntity> spec) | |
{ | |
return SpecificationEvaluator<TEntity>.GetQuery(_context.Set<TEntity>().AsQueryable(), spec); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment