Converting Domain Model types to ViewModels

architecture, asp.net-mvc, c#, type-conversion, viewmodel

Solution

Look at the nested mappings in automapper: Nested mappings

This will save you tons of time and if you are using ORM on a project, mappings will become a piece of cake in no time :)

Problem

I'm interested in discovering the different ways that developers are using to abstract their views away from their domain models. Currently I create a ViewModel for each model that I want to use in a view and I have a converter `IConverter<TIn,TOut>` to do so. What I'm noticing is that for types containing collections of other types, I have a ViewModel for each type in the heirarchy and converters that use other converters to build up the final ViewModel. As an example: Suppose I have this domain model structure that's built up with FluentNHibernate: ``` public class User { [...] public virtual IEnumerable<QuestionSubscription> QuestionSubscriptions{get;set;} } public class QuestionSubscription { public virtual bool VerifiedSubscription{get;set;} public virtual Question Question{get;set;} } ``` Given the way I'm working this I'll then have 3 ViewModels to support this and since I use my custom converters there will be a chain of conversion from User down to Question: (shortened some names for brevity) ``` _userToUserViewModelConverter.Convert(userModel) | V _qSubscriptionToViewModelConverter.Convert(userModel.QSubscriptions) | V _questionToViewModelConverter.Convert(QSubscription.Question) ``` This is working great, I'm just wondering about other ways of managing this. My first question is, do you think I'm taking the right approach by not letting my domain models touch my views? Secondly, assuming "yes" to question 1, would you use the same approach of having the converters execute other converters or would you do each one at a time in the Controller?

Original source