LiamB
LiamB

Reputation: 18586

Asp.Net MVC - Mapping Data Objects to View Model

Our current MVC project is set up to have ViewModels that encapsulate the data from the repository and pass it to the view.

When doing the mapping (In the controller) from Data Object to View model what is the best way to achieve this?

I've seen AutoMapper (http://www.codeplex.com/AutoMapper), but wondered if there was an out of the box solution?

Upvotes: 1

Views: 2127

Answers (1)

queen3
queen3

Reputation: 15501

AutoMapper seems to be the accepted (by many) solution.

And I would say, there's no such thing as "out of the box" solution in the MVC world - unlike in Ruby on Rails, for example. Framework is highly extensible but is very thin at the same time, so in lots of areas you have to invent your own "opinionated" way of doing things. Just an example of your situation, I personally have my view models:

  • Declare static ConfigureAutoMapper()
  • Have either optional Setup(realmodel) method or optional constructor
  • ViewModel(destinationViewModelType) is used on actions, and it performs conversion automatically - creating view model, calling Setup or Constructor, or invoking AutoMapper
  • ViewModel maps are created with predefined ConstructUsing that uses IoC container to instantiate so that view models gets their IoC dependencies if needed

None of the above exist in MVC out of the box. I'd say that MVC only supports ViewData-like usage "out of the box".

Upvotes: 4

Related Questions