Jak*_*sen 9 asp.net-mvc viewmodel automapper editmodel
在ASP.NET MVC项目中,我们使用AutoMapper从域模型映射到viewmodel - 有时也会在执行此操作时展平层次结构.这就像一个魅力,使我们的视图的渲染逻辑非常精简.
当我们想要从viewmodel(或postmodel或editmodel)转向域模型时,尤其是在更新对象时,会出现混淆.我们不能使用自动/双向映射,因为:
ChangeManagerForEmployee()"或类似的方法.这也在Jimmy Bogards的文章中描述:AutoMapper中的双向映射的情况,但是没有详细描述解决方案,只是他们去了:
从EditModel到CommandMessages - 从松散类型的EditModel转换为强类型的,分解的消息.单个EditModel可能会生成六个消息.
在一个类似的SO问题中,Mark Seeman在答案中提到了这个问题
我们使用抽象映射器和服务将PostModel映射到域对象
但遗漏了细节 - 概念和技术实施.
我们现在的想法是:
UpdateModel()有人可以提供一些关于它们如何从FormCollection通过editmodel/postmodel到域模型的示例吗?"CommandMessages"或"抽象映射器和服务"?
我使用以下模式:
[HttpPost]
public ActionResult Update(UpdateProductViewModel viewModel)
{
// fetch the domain model that we want to update
Product product = repository.Get(viewModel.Id);
// Use AutoMapper to update only the properties of this domain model
// that are also part of the view model and leave the other properties unchanged
AutoMapper.Map<UpdateProductViewModel, Product>(viewModel, product);
// Pass the domain model with updated properties to the DAL
repository.Update(product);
return RedirectToAction("Success");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
830 次 |
| 最近记录: |