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?


Solution 1:

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.

Solution 2:

why? 'cause the view shouldn't have the ability to use the model object!

Imagine you pass the project to a web designer to do the view layer. Suddenly he/she has the ability to mess around with your application's data through the model layer. That's not good.

So always only pass the data the view needs, instead of the object with methods.

Solution 3:

J.P. Boodhoo's article Screen Bound DTOs will help you understand the design benefit.

There is also a security benefit that I have written about.

Having a presentation model simplifies your views. This is especially important because views are typically very hard to test. By having a presentation model you move a lot of work out of the view and into the domain->presentation model. Things like formatting, handling null values and flattening object graphs.

I agree that the extra mapping is a pain but I think you probably need to try both approaches in your specific context to see what works best for you.

Solution 4:

There are even plainer concerns including the view model's ability to be specially formatted and certainly null-safe.

Solution 5:

I guess the idea is that your domain models might extend to other implementations, not just your MVC application and that would break the seperations of concerns principle. If your View Model IS your domain model then your domain model has two reasons to change: a domain change requirement AND a view requirement change.