I have created a generic repository for my MVC 3 page. I am using interfaces and a UnitOfWork. But before I set out to do this? Is this the right way to separate my databaseaccess from my viewmodels and views?
WHY I DID IT:
I want to seperate my databaseaccess from my viewmodels and my views, I also want the option to have specific methods for inserting some of my data hence the UserRepository. I also want a controlled environment using the UnitOfWork.
FEARS:
Am I over-complicating everything using these interfaces? Should I ditch the generic repository, I will use it for "basic" inserts so it's not useless by any means. I do understand that I might save some time having the generic repository, only to be creating specific repositories for some of my inserts/update/deletes.
Summary:
It consists of 6 files at the moment of which 2 are:
IRepository
GenericRepository
IUnitOfWork
UnitOfWork
IUserRepository
UserRepository
Code
IRepository:
public interface IRepository<T> where T : class
{
IEnumerable<T> BaseFetchAll();
void BaseAdd(T entity);
void BaseDelete(T Entity);
}
Repository:
public abstract class GenericRepository<T> : IRepository<T> where T : class
{
private IObjectSet<T> _dbContext;
private Entities _context;
protected DbSet<T> dbSet;
internal GenericRepository(Entities context)
{
this._context = context;
dbSet = context.Set<T>();
}
public void BaseDelete(T entity)
{
dbSet.Remove(entity);
}
public IEnumerable<T> BaseFetchAll()
{
return (IEnumerable<T>)(from x in dbSet select x).ToList<T>();
}
public void BaseAdd(T entity)
{
dbSet.Add(entity);
}
}
IUnitOfWork: Before you kick my butt, I am to implement the save,rollback etc. methods this is just to show you what I'm doing.
public interface IUnitOfWork
{
IUserRepository UserRepository { get; }
IUserFileRepository UserFileRepository { get; }
}
UnitOfWork:
public class UnitOfWork : IUnitOfWork
{
private IUserRepository _userRepository;
private Entities context = new Entities();
public IUserRepository UserRepository
{
get
{
if(this._userRepository == null)
this._userRepository = new UserRepository(context);
return this._userRepository;
}
}
}
IUserRepository:
public interface IUserRepository: IRepository<t_users>
{
IEnumerable<t_users> FetchAllUsers();
void InsertToUserTableWithSpecs();
}
UserRepository:
public class UserRepository : GenericRepository<t_users>, IUserRepository
{
private Entities dbContext;
public UserRepository(Entities context) : base(context)
{
this.dbContext = context;
}
public IEnumerable<t_users> FetchAllUsers()
{
return (IEnumerable<t_users>)(from x in dbContext.t_users select x);
}
public void InsertToUserTableWithSpecs()
{
}
}
Not a lot of code but hopefully something to give you an idea in which direction I'm going.