存储库应该返回域模型,而不是视图模型。至于模型和视图模型之间的映射,我个人使用AutoMapper,所以我有一个单独的映射层,但是这个层是从控制器调用的。
以下是典型的 GET 控制器操作的样子:
public ActionResult Foo(int id)
{
// the controller queries the repository to retrieve a domain model
Bar domainModel = Repository.Get(id);
// The controller converts the domain model to a view model
// In this example I use AutoMapper, so the controller actually delegates
// this mapping to AutoMapper but if you don't have a separate mapping layer
// you could do the mapping here as well.
BarViewModel viewModel = Mapper.Map<Bar, BarViewModel>(domainModel);
// The controller passes a view model to the view
return View(viewModel);
}
当然可以使用自定义操作过滤器来缩短它以避免重复的映射逻辑:
[AutoMap(typeof(Bar), typeof(BarViewModel))]
public ActionResult Foo(int id)
{
Bar domainModel = Repository.Get(id);
return View(domainModel);
}
AutoMap 自定义操作过滤器订阅 OnActionExecuted 事件,拦截传递给视图结果的模型,调用映射层(在我的例子中为 AutoMapper)将其转换为视图模型并将其替换为视图。视图当然是视图模型的强类型。