Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC - Database entities or ViewModels?

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).

like image 864
Alex York Avatar asked Jun 07 '12 08:06

Alex York


People also ask

Should I use ViewModels?

The ViewModel is essential when you want a separation of concerns between your DomainModel (DataModel) and the rest of your code.

Is it OK to use entities for ViewModel in ASP.NET MVC?

You can't. You need to represent different contexts as different view models because validation on those models changes depending on the screen representation.

What is the purpose of ViewModel in MVC?

ViewModel = Model that is created to serve the view. ASP.NET MVC view can't have more than one model so if we need to display properties from more than one model in the view, it is not possible. ViewModel serves this purpose. View Model is a model class that can hold only those properties that are required for a view.

What is difference between model and ViewModel in MVC?

A model is usually more closely related to how your data is stored (database, services, etc.) and the model will closely resemble those. The ViewModel on the other hand is closely related to how your data is presented to the user. It is usually a flatten version of your model, denormalized, etc.


1 Answers

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

Cons:

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

Pros:

  1. 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.
  2. 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.
  3. 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.
  4. 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.
like image 179
moribvndvs Avatar answered Oct 10 '22 01:10

moribvndvs