从视图模型到域模型的最佳映射位置在哪里?

Bre*_*ogt 14 c# asp.net-mvc automapper asp.net-mvc-3 asp.net-mvc-2

从视图模型到域模型的映射的最佳位置在哪里?通过映射我的意思是从我EditGrantApplicationViewModel到一个GrantApplication对象.

可以说我有以下操作方法(部分代码):

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

   return View("Index");
}
Run Code Online (Sandbox Code Playgroud)

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

ebb*_*ebb 24

你应该不会把您的任何映射逻辑的服务层内,因为它只是dosent属于那里.映射逻辑应该进入控制器内部而不是其他地方.

你可能会问为什么?很简单,通过将映射逻辑放在服务层中,它需要知道服务层永远不应该知道的ViewModel - 它还会降低将映射逻辑放在那里的应用程序的灵活性,因为你不能重用服务层而不需要很多黑客攻击.

相反,你应该做的事情如下:

// 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...
}
Run Code Online (Sandbox Code Playgroud)

通过如上所述,您可以使服务层更加灵活,因为它没有绑定到特定的类,并且它不知道您的viewmodel的存在.

更新:

要映射从服务层的ViewModels回到你的实体,您可能想看看Automapper价值喷油器.