I have an Asp.net MVC5 application structured like this:
Core
- Domain project
Infrastructure
- DAL project
- Utilities
UI
- 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.?
1 Answer 1
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.
-
I made a simple mock yesterday and put mapping to the ViewModel itself, it works but as you say it not really SRP friendly. I think I will just go ahead and make a ViewModel project in UI level folder and separate mapping from ViewModel itself. Much like I have with Domain models and configuration/mapping classes.Iztoksson– Iztoksson12/30/2015 07:23:34Commented Dec 30, 2015 at 7:23