Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use DTO and ViewModel all together? Or it is not possible?

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

I know DTO, ViewModel, Models. They have specific purposes. We use DTO to transfer data and ViewModel to show data to an end user. But I am confused about to use all of them together. I did a lot of Googling but did not find a complete tutorial how to use both of them all together.

I am not sure whether they can be used all together or they must have to use for specific purposes like for regular MVC we can use ViewModel and for WebAPI we will use DTO.

Can anybody explain the way to use them or any link is appreciated which focuses the use of both of them all together.

like image 712
blueMoon Avatar asked Mar 08 '23 17:03

blueMoon


2 Answers

I did a lot of Googling but did not find a complete tutorial how to use both of them all together.

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

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

Data Transfer Object(DTO) is a loosely term; you can call POCO Entity as DTO too. It is used basically when passing data from service/repository layer to controller and vice versa.

Transferring data from DTO to ViewModel is a lot of work, so we normally use AutoMapper from DTO to ViewModel and vice versa.

You could definitely share ViewModel for both MVC and WebAPI.

Can anybody explain the way to use them or any link is appreciated which focuses the use of both of them all together.

In my sample project, I have EmailTemplateModel(View Model) and EmailTemplate.

EmailTemplate class is used to transfer data from EmailTemplateService to EmailTemplateController. I then use AutoMapper to map objects.

like image 156
Win Avatar answered Mar 12 '23 06:03

Win


If you write simple CRUD application then it will be better have separated models for ORM (EF) and View, because after this your ViewModel not depend on Entity Model and you can change db tables easy without worry about presentation models.

If you write big enterprise application, where you have rich domain models, then look at CQRS pattern. (See Udi Dahan post)

After this, if you choose use this architecture pattern, it make sense have one model for View and another for ORM. (See Materialized View pattern)

like image 29
giokoguashvili Avatar answered Mar 12 '23 05:03

giokoguashvili