I'm using this pattern since a few months and I was wondering if I can make it any better.
The one thing I am not satisfied about is the dispose method. In every repository I have to add a dispose method that calls the base dispose method. Is there a way to get rid of the dispose method in every repository and just let it (automatically) call the base dispose method?
I'm using Linq2Sql.
Interface:
public interface IRepository<TEntityType> where TEntityType : class
{
TEntityType GetById(int id);
IQueryable<TEntityType> GetAll();
void Delete(TEntityType item);
void Add(TEntityType item);
}
Base:
public class BaseRepository<TEntityType> where TEntityType : class
{
private readonly DataClassesDataContext _dataContext;
protected BaseRepository()
{
_dataContext = new DataClassesDataContext();
}
protected Table<TEntityType> GetTable()
{
return _dataContext.GetTable<TEntityType>();
}
protected void SaveChanges()
{
_dataContext.SubmitChanges();
}
protected virtual void Dispose()
{
if (_dataContext != null)
{
_dataContext.Dispose();
}
}
}
Repository class:
public class FirstClassRepository : BaseRepository<FirstTable>, IRepository<FirstTable>, IDisposable
{
public FirstTable GetById(int id)
{
return GetTable().FirstOrDefault(x => x.Test == id);
}
public IQueryable<FirstTable> GetAll()
{
return GetTable();
}
public void Delete(FirstTable item)
{
GetTable().DeleteOnSubmit(item);
}
public void Add(FirstTable item)
{
GetTable().InsertOnSubmit(item);
}
public new void Dispose()
{
base.Dispose();
}
}
BaseRepository
always meant to be extended? \$\endgroup\$