如何将editmodel/postmodel变为域模型

Jak*_*sen 9 asp.net-mvc viewmodel automapper editmodel

在ASP.NET MVC项目中,我们使用AutoMapper从域模型映射到viewmodel - 有时也会在执行此操作时展平层次结构.这就像一个魅力,使我们的视图的渲染逻辑非常精简.

当我们想要从viewmodel(或postmodel或editmodel)转向域模型时,尤其是在更新对象时,会出现混淆.我们不能使用自动/双向映射,因为:

  1. 我们必须取消平坦的等级制度
  2. 域模型上的所有属性都必须是可变的/具有公共setter
  3. 来自视图的更改并不总是仅将平面属性映射回域,但有时需要调用类似" ChangeManagerForEmployee()"或类似的方法.

这也在Jimmy Bogards的文章中描述:AutoMapper中的双向映射的情况,但是没有详细描述解决方案,只是他们去了:

从EditModel到CommandMessages - 从松散类型的EditModel转换为强类型的,分解的消息.单个EditModel可能会生成六个消息.

在一个类似的SO问题中,Mark Seeman在答案中提到了这个问题

我们使用抽象映射器和服务将PostModel映射到域对象

但遗漏了细节 - 概念和技术实施.

我们现在的想法是:

  1. 在控制器的操作方法中接收FormCollection
  2. 获取原始域模型并将其展平为viewModelOriginal和viewModelUpdated
  3. 使用将FormCollection合并到viewModelUpdated中 UpdateModel()
  4. 使用一些通用帮助器方法将viewModelOriginal与viewModelUpdated进行比较
  5. A)生成CommandMessages a la Jimmy Bogard或B)通过属性和方法将差异直接变异到域模型(可能直接通过AutoMapper映射1-1属性)

有人可以提供一些关于它们如何从FormCollection通过editmodel/postmodel到域模型的示例吗?"CommandMessages"或"抽象映射器和服务"?

Dar*_*rov 2

我使用以下模式:

[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)