Question

When using MVC and converting your data into ViewModels which is the accepted way to do this?

At the moment I'm using AutoMapper to do this and its working well. However I did see in a blog article (I think it was Rob C) having a constructor on the ViewModel which takes the number of required params and then generates the ViewModel

Eg var RetViewModel = new ViewModel(MyObject);

This seems like a decent way of doing it, thoughts?

Was it helpful?

Solution

The "accepted way" is generally the way that works best for you.

I have never heard of AutoMapper and when I looked into it, what I got was that it creates magical object mapping by following a certain convention.

Screencast at: http://www.dnrtv.com/default.aspx?showNum=155

Note: I only watched about half of that screencast, so my thoughts on AutoMapper are somewhat incomplete.

I personally don't want to use it because it requires that I write extra code to map/"flatten" between object properties (code, IMO, better left in constructor logic). In the screencast example, that code is usually placed in the action methods of a controller which can lead to bloating.(I like skinny controllers/actions)

I use the method you gave in your post, having the constructor of the model take an object and do all the work.

In addition, I always create an empty constructor that takes no parameters so that I can manually set the property values of the ViewModel object.

Example:

CustomViewModel myModle = new CustomViewModle
{
    Property1 = "Something",
    Property2 = 3,
    //etc..
};

To summarize, try both ways and see what works for you. AutoMapper is a great idea and I can see it helping in many situations, however, I think at some points when you use it you'll be writing as much code using it if you were to use object constructors.

OTHER TIPS

Well, the "officially recommended" approach is to let the model binding mechanism handle that for you. That is simpler and automates the process. The model will have to expose its properties to be read-write for the binder to be able to initialize it.

The second option you're talking about will probably take benefits of making your models immutable objects. That is, you make all properties read-only and initialize them once via constructor parameters. This will require that you look into FormCollection directly to pull out the submitted values. That is more work but has its own advantages like being one type of defensive programming.

I can't say which way is better, both are options. I personally prefer the second style for now.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top