What is the difference between DTOs and ViewModels? [closed]

0
  

I can not understand their difference and what is the purpose of using AutoMapper

    
asked by Cristian Tabares 26.03.2018 в 19:17
source

1 answer

4

A ViewModel is a kind of model that you can use to work with views, example when rendering a complex form based on classes, the difference is that this class is not used by your ORM to persist data while DTOs are classes that Entity Framework maps to your DB

A very common case in which I use ViewModels is when I want to create a form that contains data of 2 or more classes, in this case I create a ViewModel with the parameters that I need and I create my form based on that ViewModel with its validations.

On the use of AutoMapper. As I explained to you, the ViewModel serves as a kind of view that we will use in order to show complex data or create custom forms that use more than one class, but when sending the data of this form based on a class in this case your ViewModel to a controller, EF does not know how to save that information since there is no such table in your database, so we use AutoMapper to separate the data from the ViewModel and assign it to each of the classes involved before saving it in your DB.

example, we have the Worker class and the User class each with their attributes and we want in a form to create a User and at the same time a Worker, if we use a Formulario strongly typed to a class we can only use a model, or Worker or User in the view, in this case you can create a ViewModel named WorkerUserViewModel with the attributes of the 2 classes and now if you can create your form based on that model with its validations through DataAnnotations and all, it is like one more class but that EF will not use it to save in BD as with Worker and User. So far the point is that TrabajadorUserviewModel collects all the data in the form and you need to separate all that and assign the data that corresponds to each class in your controller, that's where AutoMapper is used, I hope it helps you

    
answered by 26.03.2018 в 19:29