在我的ASP.NET MVC应用程序中,我使用工作单元和存储库模式进行数据访问。
使用工作单元类和在其中定义的存储库,我正在 Controller 中获取相关的实体集。以我的初学者知识,我可以想到两种获取业务模型并将其转换为 View 模型的方法。
目前,我正在使用第一种方法,但是对于具有很多属性的 View 模型,我的 Controller 代码开始显得难看且冗长。
另一方面,我在想,因为我的存储库被称为UserRepository(例如),它应该直接返回业务模型,而不是仅对单个 View 有用的某些模型。
您认为大型项目的最佳实践是哪一种?还有其他方法吗?
最佳答案
存储库应返回域模型,而不是 View 模型。至于模型和 View 模型之间的映射,我个人使用AutoMapper,所以我有一个单独的映射层,但是从 Controller 调用了该层。
以下是典型的GET Controller 操作的样子:
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事件,截获传递给 View 结果的模型,调用映射层(在我的情况下为AutoMapper)将其转换为 View 模型并将其替换为 View 。当然, View 是根据 View 模型强类型化的。
关于c# - 在哪里将业务模型转换为 View 模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11470164/