ASP.NET MVC – Mapping Domain Models to ViewModel

asp.net-mvcentity-frameworkmvvm

I have an Asp.net MVC5 application structured like this:

Core

  1. Domain project

Infrastructure

  1. DAL project
  2. Utilities

UI

  1. UI project (contains ViewModel at the moment, will probably put that
    into separate project as I expect that application will grow through
    time)

It works through Unit of work and a generic repository, injected with Unity.

My question is:

I'm strictly trying to use ViewModels for my UI Views, where should I put the logic to map Domain Model <=> ViewModel?

Should I do it in the Controller or perhaps put the mapping logic into the ViewModel itself and create methods ViewModel.FromDomainObject(DomainObject domainObject) or ViewModel.ToDomainObject(ViewModel viewModel) etc.?

Best Answer

Keep mapping implementation out of your controllers. Instead, call the thing responsible for mapping in your controller.

public ActionResult FetchSomething()
{
    var thingMapper = new ThingMapper();
    var viewModel = thingMapper.ToViewModel(service.FetchSomething());
    return View(viewModel);
}

Of course, if your ViewModel is just a property or two, you can skip the mapper.

public ActionResult FetchSomething()
{
    var thing = service.FetchSomething();
    var viewModel = new ThingViewModel { Prop1 = thing.Prop1 };
    return View(viewModel);
}

With a little luck, AutoMapper might help you map objects without writing custom mappers.

I wouldn't store mapping implementation in the ViewModels themselves. This gets awkward when one ViewModel can represent data from more than one source. It also mixes responsibilities a little too much for my tastes.