c# - 从 View 模型映射到域模型的最佳位置在哪里?

标签 c# asp.net-mvc asp.net-mvc-2 asp.net-mvc-3 automapper

将 View 模型映射到域模型的最佳位置在哪里?我所说的映射是指从我的 EditGrantApplicationViewModelGrantApplication 对象。

假设我有以下操作方法(部分代码):

[HttpPost]
public ActionResult Create(EditGrantApplicationViewModel editGrantApplicationViewModel)
{
   if (!ModelState.IsValid)
   {
      return View("Create", editGrantApplicationViewModel);
   }

   return View("Index");
}

我是否需要将 editGrantApplicationViewModel 传递给服务层方法并在该方法中进行映射?

最佳答案

您不应该将任何映射逻辑放在服务层内,因为它根本不属于那里。映射逻辑应该放在您的 Controller 内部,而不是其他任何地方。

为什么你会问?很简单,通过将映射逻辑放置在您的服务层中,它需要了解服务层永远不应该知道的 ViewModels - 它还降低了您将映射逻辑放置在那里的应用程序的灵 active ,因为您不能无需大量 hack 即可重用服务层。

相反,你应该这样做:

// Web layer (Controller)
public ActionResult Add(AddPersonViewModel viewModel)
{
    service.AddPerson(viewModel.FirstName, viewModel.LastName)
    // some other stuff...
}

// Service layer
public void AddPerson(string firstName, string lastName)
{
    var person = new Person { FirstName = firstName, LastName = lastName };
    // some other stuff...
}

通过像上面那样做,您可以使您的服务层更加灵活,因为它没有绑定(bind)到特定的类并且不知道您的 View 模型的存在。

更新:

要将从服务层返回的实体映射到 ViewModel,您可能需要查看 AutomapperValue Injecter .

关于c# - 从 View 模型映射到域模型的最佳位置在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5610887/

相关文章:

c# - 如何检查输入 IP 是否属于特定 IP 范围

c# - 在新的 not null 测试中使用 ref 原则

c# - 使用 Foq 模拟具有显式实现接口(interface)的类

c# - 具有动态参数的 MVC 分部方法

asp.net - 如何使用 ASP.Net -- Html.ActionLink()

c# - 对于每个请求,我所有注入(inject)的 Controller 的构造函数都被命中 4 次

c# - 如何在不将整个图像加载到内存的情况下加载 TIFF 图像的一部分?

c# - asp.net mvc生成数据下载文件

c# - ASP.NET MVC : does AntiForgeryToken work in mono?

c# - 更改编辑 |详情 |删除操作链接,为 508 位合规读者提供替代文本