【发布时间】:2012-02-15 23:16:05
【问题描述】:
我在弄清楚如何使这个存储库模式起作用时遇到了一些麻烦。
简而言之,我的解决方案看起来像这样......
ASP.Net MVC
^
|
Business Logic
^
|
Data Access
(Repositories and Unit of Work)
^
|
Entity Framework Models
我有一个引用角色表的用户表。
在我的 MVC 应用程序中,我使用 GetAllUsers 调用 BLL。 BLL 中的代码如下所示:
public List<User> GetAllUsers()
{
using (UnitOfWork uow = new UnitOfWork())
{
UserRepository userRepository = new UserRepository(uow);
return userRepository.GetAll().ToList();
}
}
UserRepository 派生自 GenericRepository,它有一个 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();
}
}
它将用户列表返回到我的 MVC 应用程序,但是当我尝试访问角色引用时,由于延迟加载,它尚未加载。
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();
}
我尝试在 GetAllUsers 上放置一个 .Include(Roles),但在 IQueryable 上没有 .Include。
从理论上讲,我是否认为 MVC 应用程序不需要了解有关上下文或数据访问的任何信息? 其次,在离开 BLL 之前,我应该如何将这个角色引用包含在我的图表中?
【问题讨论】:
标签: linq asp.net-mvc-3 entity-framework repository-pattern unit-of-work