How do I use DTO and ViewModel together? Or is it impossible?

Note. My question is using DTO, ViewModel in .NET / C # project.

I know DTO, ViewModel, Models. They have specific goals. We use DTO to pass data and ViewModel to display data to the end user. But I am embarrassed to use them all together. I've done a lot of Googling but haven't found a complete tutorial on how to use both of them together.

I'm not sure if they can be used all together or they should be used for specific purposes, for example, for normal MVC we can use ViewModel, and for WebAPI we will use DTO.

Can someone explain how to use them, or any link appreciated that focuses on using both of them together.

+3


source to share


2 answers


I've done a lot of Googling but haven't found a complete tutorial on how to use both all together.

View <----------- -> Controller <-----------> Service/Repository
        ViewModel                    DTO
            ^--------AutoMapper-------^     

      

The ViewModel is mainly used when passing data from Controller to View .

Data Transfer Object (DTO) is a loose term; you can also call POCO Entity as DTO. It is mainly used when transferring data from the service / repository layer to the controller and vice versa.

Passing data from DTO to ViewModel is a lot of work, which is why we usually use AutoMapper . DTO - ViewModel and vice versa.



You can definitely share the ViewModel for MVC and WebAPI.

Can someone explain how to use them, or any link appreciated which focuses on using both of them.

In my sample project, EmailTemplateModel and EmailTemplate .

The EmailTemplate class is used to pass data from the EmailTemplateService to the EmailTemplateController . Then I use AutoMapper to map objects.

+1


source


If you are writing a simple CRUD application, then it would be better to separate models for ORM (EF) and View, because after that you ViewModels are independent of Entity Model and you can easily modify db tables without worrying about presentation models.

If you are writing a large enterprise application where you have rich domain models, take a look at the CQRS pattern. (See Udi Dahan's post )



After that, if you decide to use this architecture pattern, it makes sense to have one model for the View and ORM. (See Materialized View Template )

+1


source







All Articles