Alex Rivera | Logout

In Asp.net MVC, is it advisable for viewmodels to derive from domain models?

Asked 2010-08-23T21:33:41.693
11

(I am using ASP.Net MVC, but this seems like a more generic MVC question)

Say you have a domain model representing a person, and you have a view for editing a person. Included in the Person domain object is a State of Residence property, and in the view you want a dropdown that lists states.

Is there any reason not to create a view model that derives from the domain model and simply includes properties for the UI spiciness the view requires? If so, why would not not want to do this?

TIA

Edit
Report

3 Answers

7

I would think that deriving a view model from a domain model would introduce coupling that MVC was intended to avoid; however, that said, do what makes the most sense for your application.

I prefer to have view models separate because doing so leaves me free to dramatically change the domain model and get improved compile time support for remapping my view model to the new domain model.

answered 2010-08-23T21:37:52.873
2

No, you don't really want to do this.

A big part of the reason to use ViewModels is because your domain entities tend to be big, spiky, complex and tied to persistence mechanisims. All leading for them to have strange, interesting or destructive behaviors when they encounter things such as the DefaultModelBinder.

By using much simpler ViewModel classes, you can avoid the bulk of these problems while also further decoupling your UI layer from your domain model.

Now, what you should do is provide easy means to generate a ViewModel from a Domain Entity or to updated a Domain Entity from a ViewModel.

answered 2010-08-23T21:38:07.953
-1

I disagree with most of the advice here.

I think that your domain model should be clean and a viewmodel does what it has to. If your view needs a person and the time in London i dont see the problem with doing this:

ExampleViewModel : Person {
 Public DateTime LondonTime { get; set;}
}

Or

AnotherViewModel 
{
 Public Person SomeGuy { get; set;}
 Public List<Kitty> Cats{ get; set;}
}

If your view needs a person and a list of kitties

This keeps your domain clean; the time of London is not related to a person however on your view you still need get the data. This is the whole point of a view model imho.

answered 2010-08-24T07:10:59.623

Your Answer