emr*_*azi 17 c# asp.net-mvc entity-framework unit-of-work repository-pattern
在我的ASP.NET MVC应用程序中,我使用工作单元和存储库模式进行数据访问.
使用工作单元类和在其中定义的存储库,我在控制器中获取相关的实体集.凭借我的初学者知识,我可以想到两种方法来获取业务模型并将其转换为视图模型.
目前我正在使用第一种方法,但我的控制器代码开始看起来很丑,很长时间用于具有大量属性的视图模型.
另一方面,我在想,因为我的存储库名为UserRepository(例如),它应该直接返回业务模型,而不是仅对单个视图有用的模型.
您认为哪一项更适合大型项目?还有另一种方法吗?
谢谢.
Dar*_*rov 21
存储库应返回域模型,而不是视图模型.就模型和视图模型之间的映射而言,我个人使用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);
}
Run Code Online (Sandbox Code Playgroud)
当然可以使用自定义动作过滤器缩短,以避免重复的映射逻辑:
[AutoMap(typeof(Bar), typeof(BarViewModel))]
public ActionResult Foo(int id)
{
Bar domainModel = Repository.Get(id);
return View(domainModel);
}
Run Code Online (Sandbox Code Playgroud)
AutoMap自定义动作过滤器订阅OnActionExecuted事件,拦截传递给视图结果的模型,调用映射层(在我的情况下为AutoMapper)将其转换为视图模型并将其替换为视图.该视图当然是对视图模型的强类型.
| 归档时间: |
|
| 查看次数: |
8021 次 |
| 最近记录: |