MVC: Data Models and View Models

Erik Forbes picture Erik Forbes · Jan 24, 2009 · Viewed 11.7k times · Source

I've read some MVC advice in the past regarding models stating that you should not reuse the same model objects for the domain and the view; but I haven't been able to find anyone willing to discuss why this is bad.

It is my opinion that creating two separate models - one for the domain, one for the view - and then mapping between them creates a lot of duplication, plus tedious mapping code (some of which might be alleviated by things like AutoMapper) that will likely be error prone.

What makes having a separate model for the two concerns worth the trouble of duplication and mapping code?

Answer

Jimmy Bogard picture Jimmy Bogard · Jan 24, 2009

At its heart, two models is about Separation of Concerns. I want my View to work off of a single Model. I want my Domain Model to represent the conceptual model I build with the domain experts. ViewModel often has technical constraints. Domain Model is about POCO, and not being bound by technical constraints of either data shown (View) or persisted (in a DB or otherwise).

Suppose I have three entities shown on a screen. Does that mean I need to force a relationship between the three? Or just create a ViewModel component object that contains all three items. With a separate ViewModel, View concerns are separated from my domain.