On a current project we are experimenting with different approaches to populate ViewModel objects coming from Entity Framework. Currently, upon receiving a list of EntityModel we use an extension method:
public static IEnumerable<ViewModel> GetViewModel(this IEnumberable<EntityModel> data){}
This extension method is defined in the same namespace as the ViewModel objects so as to keep it closely tied to the ViewModel and a specific controller in ASP.NET MVC.
Specifically, we are looking for feedback from the development community on :
- Is this an appropriate place to be using an extension method. We are concerned because it seems like a break from OOP, and more of a ‘band-aid’ solution.
- What are ‘Tried and Tested’ ways of populating
ViewModelobjects fromEntityModelobjects. We have tried the following:- Manually assigning each field in the controller (too much coupling between view and controller)
- Passing in Entity/ViewModel object into View Model contructor (Best so far, but ViewModel is coupled to Entity)
Thanks in advance for any suggestions/help.
It is advisable to decouple the mapping between EntityModel and ViewModel from either. If the mapping plumbing is coupled to the view, it is difficult to drop in a new view for a different purpose in the future. If tied to the EntityModel, it is difficult to drop in a new entity model, using the same view. Either way, it is more difficult to independently evolve the view model and entity model if the mapping infrastructure is tied to either.
I would suggest that mapping should be an independent architectural building block, and further suggest you have a look at AutoMapper as an implementation of that component.
http://automapper.codeplex.com/