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

后端 未结 4 480
鱼传尺愫
鱼传尺愫 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条回答
  •  盖世英雄少女心
    2021-02-01 08:20

    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.

    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.

    Instead you should do something like:

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

    UPDATE:

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

提交回复
热议问题