DTO = ViewModel?

autonomatt picture autonomatt · Dec 30, 2009 · Viewed 43.9k times · Source

I'm using NHibernate to persist my domain objects. To keep things simple I'm using an ASP.NET MVC project as both my presentation layer, and my service layer.

I want to return my domain objects in XML from my controller classes. After reading some posts here on Stack Overflow I gather DTOs are the way to go. However, I've also come across posts talking about the ViewModel.

My question: Are Data Transfer Objects and ViewModels the same thing? Or is a ViewModel a kind of sub pattern of a DTO?

Answer

Daniel Auger picture Daniel Auger · Dec 30, 2009

The canonical definition of a DTO is the data shape of an object without any behavior.

ViewModels are the model of the view. ViewModels typically are full or partial data from one or more objects (or DTOs) plus any additional members specific to the view's behavior (methods that can be executed by the view, properties to indicate how toggle view elements etc...). You can look at the viewmodel as all the data for a view plus behaviors. ViewModels may or may not map one to one to business objects or DTOs.

By the way, NHibernate projections come in handy if a certain viewmodel needs a subset of the data from a persisted object.