Reputation: 30165
I'm looking at a guideline which says "automapper should be used to map the model to the view model." Why such guidance?
Why not just have the model be a property of the view model? For example, I could paginate a contact list with a view model like this:
class ContactListPaginatedViewModel {
public Contact myContact; //the model object
public PageInfo pageInfo;
}
Even if I needed a post-back to update contact info - the model binder will figure this out easily. And if I need to have certain fields/properties omitted from binding (via post-back or otherwise) then I can simply use the Bind annotation with "inclusions/exclusions."
Is there some larger issue I'm missing that would suggest a manual mapping process (where all the properties of a model are duplicated on the view model) is desireable?
The best I can figure is that the model may have dozens of properties that are not needed by the view (or the view model)...but even in that case the aforementioned guidance still doesn't make sense.
Insights?
Upvotes: 0
Views: 960
Reputation: 4401
I almost always keep a model reference in my ViewModels. If I need some extra properties, I just add them to my viewmodel. It's fine IMO.
Upvotes: 0
Reputation: 93424
Because it's bad practice to send your data entites directly to the view. There are a number of reasons for this, including security reasons. But there are also more practical reasons, such as being able to apply view model attributes (something you can't do when your entities are autogenerated, although there are ways around that such as with buddy classes).
In general. You want a view model that is specific to your view. This view model should be mapped to your business object. Whether your business object is different from your entity object is more of a gray area, but there should be a definite distinction between view model and business model.
Upvotes: 0
Reputation: 56429
Usually, if you have a dto class it is best practice to provide a View Model with only the properties that you need for the model. This means that you only actually specify properties for what you actually use, say for example I had a Client
object with 20 fields and I needed the Id
and the FullName
, it'd be overkill to include the entire Client
object in the model, it's better to just specify the properties you need in that model.
Also, from an architectural point of view, do you really want to expose your DTO classes to the view? In most cases some kind of Service layer is used as an interim communication point between both the DTO classes and the views themselves, which in turn would populate the view model for you.
Upvotes: 1