I’m having a bit of trouble figuring out how to make this repository pattern work.
In a nutshell, my solution looks something like this…
ASP.Net MVC
^
|
Business Logic
^
|
Data Access
(Repositories and Unit of Work)
^
|
Entity Framework Models
I have a Users table with a reference to a Roles table.
In my MVC app, I call the BLL with a GetAllUsers. The code in the BLL looks like this:
public List<User> GetAllUsers()
{
using (UnitOfWork uow = new UnitOfWork())
{
UserRepository userRepository = new UserRepository(uow);
return userRepository.GetAll().ToList();
}
}
The UserRepository derives from GenericRepository, which has a GetAll()
public class GenericRepository<T> : IGenericRepository<T> where T : class
{
private IUnitOfWork _uow = null;
public GenericRepository(IUnitOfWork uow)
{
_uow = uow;
}
public virtual IQueryable<T> GetAll()
{
return _uow.Set<T>().AsQueryable();
}
}
It returns a list of users to my MVC app, but when I try and access the Role reference, it hasn’t loaded yet due to lazy loading.
public ActionResult Index()
{
BusinessLogic.Account blAcct = new BusinessLogic.Account();
List<User> users = blAcct.GetAllUsers();
string firstName = users.FirstName; // Works fine
string role = users.Roles.RoleName; // Fails because the context is closed.
return View();
}
I’ve tried to put an .Include(Roles) on the GetAllUsers, but .Include isn’t available on IQueryable.
Theoretically speaking, am I right in thinking that the MVC app shouldn’t need to know anything about the context or the data access?
And second, how should I be including this Roles reference in my graph before it leaves the BLL?
You are right in thinking your MVC application, given your current application architecture, should not be concerned with the
DataContextand data retrieval.A solution may be to add another
Repositorymethod that eagerly loads yourRoles:public IList<Users> GetAllUsersWithRoles()Then selectively use the method that is appropriate, given the context.