Previous question: BaseRepository for EF6
I've update my code. Is it correct now? I've changed IEnumerable
to IQueryable
.
public interface IRepository<T> : IDisposable
{
T Get(Expression<Func<T, bool>> predicate);
IQueryable<T> GetWhere(Expression<Func<T, bool>> predicate = null);
void Add(T entity);
void Delete(T entity);
void DeleteWhere(Expression<Func<T, bool>> predicate);
void Update(T entity);
void Save();
}
public class BaseRepository<T> : IRepository<T> where T : class
{
private readonly DbContext _dbContext;
public BaseRepository(DbContext dbContext)
{
_dbContext = dbContext;
}
public T Get(Expression<Func<T, bool>> predicate)
{
return GetWhere(predicate).FirstOrDefault();
}
public IQueryable<T> GetWhere(Expression<Func<T, bool>> predicate = null)
{
IQueryable<T> result = _dbContext.Set<T>();
return (predicate == null) ? result : Queryable.Where<T>(result, predicate);
}
public void Add(T entity)
{
_dbContext.Entry(entity).State = EntityState.Added;
}
public void Delete(T entity)
{
_dbContext.Entry(entity).State = EntityState.Deleted;
}
public void DeleteWhere(Expression<Func<T, bool>> predicate)
{
IQueryable<T> entities = GetWhere(predicate);
foreach (T entity in entities)
Delete(entity);
}
public void Update(T entity)
{
_dbContext.Entry(entity).State = EntityState.Modified;
}
public void Save()
{
_dbContext.SaveChanges();
}
public async void SaveAsync()
{
await _dbContext.SaveChangesAsync();
}
public void Dispose()
{
if (_dbContext != null)
_dbContext.Dispose();
}
}