Created
February 1, 2013 22:26
-
-
Save chribben/4694587 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 interface IRepository<TEntity> where TEntity : class | |
{ | |
IEnumerable<TEntity> Get( | |
Expression<Func<TEntity, bool>> filter = null, | |
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null, | |
string includeProperties = ""); | |
TEntity GetById(object id); | |
void AddOrUpdate(TEntity entity); | |
void Delete(object id); | |
void Delete(TEntity entityToDelete); | |
void Update(TEntity entityToUpdate); | |
} | |
public class Repository<TEntity> : IRepository<TEntity> where TEntity : class | |
{ | |
private readonly DbContext _context; | |
private readonly DbSet<TEntity> _dbSet; | |
public Repository(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, | |
string includeProperties = "") | |
{ | |
IQueryable<TEntity> query = _dbSet; | |
if (filter != null) | |
{ | |
query = query.Where(filter); | |
} | |
foreach (string includeProperty in includeProperties.Split | |
(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) | |
{ | |
query = query.Include(includeProperty); | |
} | |
if (orderBy != null) | |
{ | |
return orderBy(query).ToList(); | |
} | |
else | |
{ | |
return query.ToList(); | |
} | |
} | |
public virtual TEntity GetById(object id) | |
{ | |
return _dbSet.Find(id); | |
} | |
public virtual void AddOrUpdate(TEntity entity) | |
{ | |
_dbSet.AddOrUpdate(new []{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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment