Where is the best place to map from view model to domain model?

后端 未结 4 482
鱼传尺愫
鱼传尺愫 2021-02-01 07:41

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

4条回答
  •  梦毁少年i
    2021-02-01 08:24

    I would personally never pass a view model to the service layer. If you go down that route your service ends up having direct knowledge about what is displayed on the view. This would cause changes in your viewmodel to cause changes in your service layer.

    For example: Let's say you decided to add a SelectList to your view model for reason for grant edit.

    public class EditGrantApplicationViewModel
    {
       //...
       public SelectList ReasonForEdit {get;set;}
       //...
    }
    

    This could be a perfectly valid requirement, but ask yourself does having a SelectList pass to the Service Layer make sense? A select list is more of a UI domain and doesn't really mean anything to the service layer. The service layer only cares about the reason not the select list.

    I would take your view model, digest the information needed and then pass that unit to your service layer.

    [HttpPost]
    public ActionResult Create(EditGrantApplicationViewModel editGrantApplicationViewModel)
    {
       if (!ModelState.IsValid)
       {
          return View("Create", editGrantApplicationViewModel);
       }
    
       GrantApplication grantApplication = new GrantApplication();
       grantApplication. // other fields.
       grantApplication.Reason = editGrantApplicationViewModel.ReasonForEdit.SelectedValue;
       grantApplication. // other fields.
       _someService.EditApplication(grantApplication);
    
       return View("Index");
    }
    

    If you haven't looked yet check out AutoMapper as it can help in doing between view model's, dto's and other classes.

提交回复
热议问题