GenricRepository Sample No. 1
public abstract class GenericRepository<C, T> : IGenericRepository<T> where T : class where C : DbContext, new() { private C _entities = new C(); public C Context { get { return _entities; } set { _entities = value; } } public virtual IQueryable<T> GetAll() { IQueryable<T> query = _entities.Set<T>(); return query; } public IQueryable<T> FindBy(System.Linq.Expressions.Expression<Func<T, bool>> predicate) { IQueryable<T> query = _entities.Set<T>().Where(predicate); return query; } public virtual void Add(T entity) { _entities.Set<T>().Add(entity); } public virtual void Delete(T entity) { _entities.Set<T>().Remove(entity); } public virtual void Edit(T entity) { _entities.Entry(entity).State = System.Data.EntityState.Modified; } public virtual void Save() { _entities.SaveChanges(); } }
This is so nice because of some factors I like:
- This implements so basic and ordinary methods
- If necessary, those methods can be overridden because each method is virtual.
- As we newed up the DbContext class here and expose it public with a public property, we have flexibility of extend the individual repositories for our needs.
- As we only implement this abstract class only to our repository classes, it won’t effect unit testing at all. DbContext is not in the picture in terms of unit testing.
So, when we need to implement these changes to our concrete repository classes, we will end up with following result:
public class FooRepository : GenericRepository<FooBarEntities, Foo>, IFooRepository { public Foo GetSingle(int fooId) { var query = GetAll().FirstOrDefault(x => x.FooId == fooId); return query; } }
public class BarReposiltory : GenericRepository<FooBarEntities, Bar>, IBarRepository { public Bar GetSingle(int barId) { var query = Context.Bars.FirstOrDefault(x => x.BarId == barId); return query; } }
Very nice and clean. Inside BarRepository GetSingle method, as you see I use Context property of GenericRepository<C, T> abstract class to access an instance of DbContext.
So, how the things work inside our ASP.NET MVC project? this is another story but no so complicated. I will continue right from here on my next post.
Comments
Post a Comment