哪里是从视图模型映射到域模型的最佳地点? [英] Where is the best place to map from view model to domain model?

查看:157
本文介绍了哪里是从视图模型映射到域模型的最佳地点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在哪里是做从视图模型映射到域模型的最佳地点?通过映射我的意思是从我的 EditGrantApplicationViewModel GrantApplication 对象。

Where is the best place to do mappings from view model to domain model? By mappings I mean from my EditGrantApplicationViewModel to a GrantApplication object.

让我们说,我有以下操作方法(部分code):

Lets say that I have the following action method (partial code):

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

   return View("Index");
}

我是否需要通过 editGrantApplicationViewModel 来一个服务层的方法,并在方法做映射?

Do I need to pass editGrantApplicationViewModel to a service layer method and do the mappings in the method?

推荐答案

您应该的不可以将您的任何映射逻辑的服务层内,因为它只是dosent属于那里。映射逻辑应该去你的控制器内,无处。

You should not place any of your mapping logic inside the service layer since it simply dosent belong there. The mapping logic should go inside your controller and nowhere else.

为什么你可能会问?很简单,通过将映射逻辑在你的服务层,它需要知道哪些服务层NEVER EVER应该意识到的ViewModels - 也可以减少您将映射逻辑在那里,​​因为你不能应用的灵活性重用服务层没有很多的黑客。

Why you might ask? Simple enough, by placing the mapping logic in your service layer, it needs to know about the ViewModels which the service layer NEVER EVER should be aware of - also it reduces the flexibility of the app that you place the mapping logic in there since you cant reuse the service layer without a lot of hacks.

相反,你应该这样做:

// 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...
}

这样做如上,你让你的服务层更灵活,因为它不绑定到一个特定的类,它不知道您的视图模型的存在。

By doing like above, you make your service layer more flexible since it's not bound to a particular class and it's not aware of the existence of your viewmodel.

更新:

要映射您的实体从服务层的ViewModels回来,你可能想看看 Automapper 或< A HREF =HTTP://valueinjecter.$c$cplex.com/>值喷油器

To map your Entities returned from the service layer to ViewModels, you might want to take a look at Automapper or Value Injecter.

这篇关于哪里是从视图模型映射到域模型的最佳地点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆