I have a question about the Repository pattern:
public abstract class RepositoryBase<T> : IDisposable, IRepository<T> where T : class, IEntity
{
/// <summary>
/// For iterations using LINQ extension methods on the IQueryable and IEnumerable interfaces
/// it is required that the context which was used to make the query was not disposed before the iteration
/// otherwise it will throw an exception
/// </summary>
private Context _context;
protected Context Context
{
get { return _context ?? (_context = new Context()); }
}
public virtual void AddOrUpdate(T entity)
{
var dbSet = Context.Set<T>();
if (dbSet.Contains(entity))
entity.ChangeDateTime = DateTime.Now;
else
entity.AddeDateTime = DateTime.Now;
Context.Set<T>().AddOrUpdate(entity);
Context.SaveChanges();
}
public virtual void Delete(T entity)
{
Context.Set<T>().Remove(entity);
Context.SaveChanges();
}
public void Drop()
{
var dbSet = Context.Set<T>();
foreach (var entity in dbSet)
dbSet.Remove(entity);
Context.SaveChanges();
}
public virtual IQueryable<T> Find(Expression<Func<T, bool>> predicate)
{
return Context.Set<T>().Where(predicate);
}
public IEnumerable<T> GetAll()
{
return Context.Set<T>();
}
public void Dispose()
{
if (_context != null)
{
_context.Dispose();
_context = null;
}
}
}
Why I am not embracing each method implementation with a using
and disposing the Context
as soon as the query is done?
Some of my methods, as Find
and GetAll
return collections. I would want to be able to iterate through them using LINQ, only this is not possible if the Context is disposed, as it would be in the original Repository model.
Is this the best approach to go around this issue?
IEntity
just a marker interface? \$\endgroup\$