Sunny
Sunny

Reputation: 4809

Use view models or DB models in ASP.NET MVC 5

In one of the MVC 5 tutorial, they have declared the validation attributes directly on the models. Also, they are passing the model directly to the view. Previously, we have used view models to handle this kind of behavior. Please provide your thoughts which approach to follow.

http://www.asp.net/mvc/tutorials/mvc-5/introduction/adding-validation

Upvotes: 1

Views: 416

Answers (2)

Marian Ban
Marian Ban

Reputation: 8168

Personally i prefer the view model approach because:

  1. it allows me to select only fields which i actually need (i don't want to load the whole entity but only a subset of columns which i map to view model with Select(x => new ViewModel() { PropName = x.PropName }). This gives me better performance
  2. my view models depends on the user interface (business logic) rather then DB tables structure, which gives me more flexible solution and i can easily switch to different data storage.
  3. i can easily extend my view models with new properties/methods
  4. it helps me to avoid N+1 Select problem

When to not use view models?

Basically only in cases when you want to quickly try something out say you are building a prototype which will be not used in production environment.

Upvotes: 1

Captain Kenpachi
Captain Kenpachi

Reputation: 7215

The better option is to use ViewModels. It's better because you have more control over what gets displayed where.

When you start to build applications that are NOT simply data entry, you run the risk of having to do something silly like the following:

There is a User table with 30 fields for anything from password, date entered, date last updated, delivery address, email, policiy number, etc.

The client asks you to build a Forgot Password page. If you use a DB object like the tutorials show, you're going to have to put the other 29 fields in hidden fields and pass them along.

That's the most basic problem you'll run into. Real world problems are much worse than that. Especially when you start building complex master-detail forms.

Upvotes: 0

Related Questions