【发布时间】:2017-12-05 10:02:15
【问题描述】:
我正在使用带有 EF6 的 MVC 5 来开发应用程序。我正在遵循存储库设计模式。像往常一样,有一个 Generic Repository 层,它有一个类型参数 GenericRepository。存储库包含 GetAll 函数:
public virtual List<T> GetAll()
{
IQueryable<T> query = _entities.Set<T>();
return query.ToList();
}
此存储库已从服务层调用。在服务层还有一个叫做GetAll()的函数。函数如下:
public List<Student> GetAll()
{
return _unitOfWork.StudentRepository.GetAll();
}
存储库一次处理单个实体。在此示例中,我仅从 Student 表中检索数据。我的问题是,如果我想从多个表中检索数据,比如 Student Department 和 Country 并将其显示在视图中,这怎么可能?我的控制器代码是这样的:
public ActionResult Index()
{
return View(student.GetAll());
}
我应该如何以及在何处包含“位置”和“州”实体。我也有一个 UnitOfWork 层。图层是这样的:
public class UnitOfWork : IUnitOfWork
{
private readonly ConnString _context;
private IGenericRepository<Student> studentRepository;
private IGenericRepository<Department> departmentRepository;
private IGenericRepository<Country> countryRepository;
public UnitOfWork()
{
this._context = new ConnString();
}
public IGenericRepository<Student> StudentRepository
{
get { return this.studentRepository ?? (this.studentRepository = new GenericRepository<Student>(_context)); }
}
另一个问题是,如果我想在视图中生成下拉列表(例如,部门和国家),我该怎么做?
任何帮助都将被接受。
谢谢 帕萨
【问题讨论】:
-
如果我理解正确,理想情况下,您的服务层或您的控制器可以协调从多个存储库获取数据,将它们组合到单个实体中(如果您的存储库方法返回
IQueryable<T>而不是集合或通过基于父数据有条件地查询每个存储库)并将其传回。 -
在服务层中,我将“
”实体作为 GetAll() 函数中的列表返回。学生是单一实体。我需要像 这样的东西。这种模式怎么可能? -
我相信您刚刚发现了为什么 EF 使用具有多种实体类型的单个存储库:DbContext。
标签: entity-framework model-view-controller repository-pattern