MVC 存储库模式,其中数据将从多个 table

MVC Repository pattern where data will be loaded from multiple table

我正在使用带 EF6 的 MVC 5 来开发应用程序。我正在遵循存储库设计模式。像往常一样,有一个通用存储库层,它有一个类型参数,GenericRepository<'T'>。存储库包含 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 table 检索数据。我的问题是,如果我想从多个 table 中检索数据,比如 Student Department 和 Country 并将其显示在视图中,这怎么可能?我的控制器代码是这样的:

        public ActionResult Index()
        {
            return View(student.GetAll());
        }

我应该如何以及在何处包含 "Location" 和 "State" 实体。我还有一个 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)); }
        }

另一个问题是,如果我想在视图中生成下拉列表(例如,部门和国家),我该怎么做?

我们将感激地接受任何帮助。

谢谢 帕萨

首先。存储库模式不包装 tables。它包装域实体。它们可能存储也可能不存储在单个 table.

对于您的场景,控制器的工作是从模型(业务层)获取信息并使其适应视图的要求。

因此我会这样做:

var students = _studentRepos.GetStudentsInSchool(schoolId);
var departmentIds = students.Select(x=>x.DepartmentId).Distinct();
var departments = _departmentRepos.GetAll(departmentIdS);
var countryIds = studens.Select(x=>x.CountryId).Distinct();
var countries = _countryRepos.GetAll(countryIds);

var items = new List<StudentSummaryModel>();
foreach (var student in studens)
{
    var item = new StudentSummaryModel(student);
    item.CountryName = countries.First(x=>x.Id == student.CountryId).Name;
    item.DepartmentName = departments.First(x=>x.Id == student.DepartmentId).Name;
    items.Add(item)
}

return View(items);

代码合理易读,业务领域分离。