0

I have Api project, business project and database context.

I am thinking of design like this:

  • viewmodels in api project, and mappings with automapper. Automapper will here map viewmodel to business dto model
  • dto models in business project, and mappings with automapper. Automapper will here map dto model to entity model (database).

Question 1: Should I use OperationViewModel or OperationRequestModel(ResponseModel) in api project?

Question 2: Is additional mapping between viewmodel and dto model overkill, or is it good practice to separate those concerns and decouple even more, or should I map dto models with entity models and use those dto models in api project?

sensei
  • 7,044
  • 10
  • 57
  • 125

1 Answers1

1

Firstly, I would like to congratulate you on 'getting it'. So many projects I see have the database access in the UI layer!!

Initially, you may feel that having different (but almost identical) classes for ViewModel, Business and data layers a pain, but this is where AutoMapper is brilliant. Most of the time, you don't need to do anything and it just works.

Once your code gets a bit more meat on the bone, you will find it easier to add database fields without having to worry about the effects on your view model, and to create view models that are exactly what the view requires, without having to worry about database fields. Win-win. I would also create a separate view model for each function, even if they are identical (use inheritance if required, but make sure you have a different class each time).

IMO, the models should be exposed by the layer that creates and consumes them, so the ViewModel should have XXXViewModel, the businesss layer have XXXDto etc.

public IndexViewModel Index()
{
    var vm = new IndexViewModel()
    {
        Items = _mapper.map<List<Item>>(_service.GetSomeData())
    };
    return vm;
}
public GetViewModel Get(int id)
{
    var vm = _mapper.Map<GetViewModel>(_service.get(id));
    return vm;
}
Neil
  • 11,059
  • 3
  • 31
  • 56
  • great thanks, recreating viewmodel if similar fields (for example for adding and updating in crud) is good or bad is dilemma as well. for example if we save some fields on creation automatically(not via client), and then when updating, we have to update them via client. So I think I prefer duplication(separation of viewmodles) over inheritance, but I think it is personal opinion - have a look on this https://stackoverflow.com/questions/6954102/asp-net-mvc-architecture-viewmodel-by-composition-inheritance-or-duplication – sensei Jun 05 '17 at 12:53