我正在构建我的第一个MVC应用程序。我知道由于关注点的分离,我不应该在ViewModel构造函数中查询数据,并且我目前正在重构应用程序以修复ViewModel(我正在将dbContext传递给它们)。同时,我想避免重复自己。我有其他ViewModel和控制器操作中使用的ViewModel。
我该如何实现?
此ViewModel曾经有一个构造函数,该构造函数使用DbContext查询数据库并将检索到的列表分配给属性:
BusinessClientRelationshipsViewModel.cs
public class BusinessClientRelationshipsViewModel
{
public int BusinessId { get; set; }
public IEnumerable<SelectListItem> Clients { get; set; }
public IEnumerable<SelectListItem> Businesses { get; set; }
public IEnumerable<SelectListItem> Relationships { get; set; }
public IEnumerable<RelatedClientsListViewModel> RelatedClientsList { get; set; }
}
我摆脱了DbContext并介绍了存储库/工作模式单元。我还从ViewModel中删除了构造函数。在我的控制器中,我像这样初始化ViewModel:
BusinessClientRelationships.cs
public ActionResult List(int id)
{
var viewModel = new BusinessClientRelationshipsViewModel()
{
BusinessId = id,
RelatedClientsList = _unitOfWork.ClientBusinessRelationships.GetRelatedClientsList(id),
Clients = _unitOfWork.Clients.GetSelectListItems(),
Businesses = _unitOfWork.Businesses.GetSelectListItems(),
Relationships = _unitOfWork.Relationships.GetSelectListItems()
};
return View("_BusinessClientRelationships", viewModel);
}
但是,我还有其他使用上面ViewModel(用于局部视图)的ViewModel(用于父视图)。我的问题是我不知道如何以一种干净的方式初始化BusinessClientRelationshipsViewModel(每次执行时都不会重复自己):
BusinessDetailsViewModel.cs
public class BusinessDetailsViewModel
{
public Business Business { get; set; }
public BusinessClientRelationshipsViewModel BusinessClientRelationshipsViewModel { get; set; }
public BusinessAddressChangesViewModel BusinessAddressChangesViewModel { get; set; }
}