ASP.NET MVC - Database entities or ViewModels?

asp.net-mvc, asp.net-mvc-3, orm, viewmodel

Solution

Definitely use view models in your views, and use something like `AutoMapper` to create view models from entities easily.

Cons:

- Sometimes it feels like you are duplicating code, specifically, when the view model and the entity have the exact same properties

Pros:

- You often need to represent an object in a simpler format (often called flattening), but you need full fidelity on the server side. This allows you to transition between the two without mucking up your domain model with presentation cruft.

- Aggregate roots often have a lots of value objects and additional entities that are irrelevant to a specific view, and omitting them in a view model makes it easier to work with.

- Your entities will have lots of two way references that are sensible in terms of an API, but create pure hell when serializing them for JSON, XML, etc. View models will eliminate these circular references.

- You may often use the same entity but in different ways for different views. Trying to balance both needs on one type can create a huge mess.

Problem

I am currently working on an ASP.NET MVC project. Some developers on the team want to bind the auto-generated database entities directly to the Views. Other developers want to create tailor-made ViewModel's and bind those to the Views. Objectively, what are the pros and cons of both approaches? (By "database entities" I am referring to the auto generated classes that an ORM framework generates, such as LINQ to SQL, Entity Framework or LLBLGen).

Original source