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

3

5

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.

Immitigable answered 28/6, 2017 at 19:27 Comment(0)
T
7

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.

Tail answered 28/6, 2017 at 21:7 Comment(0)
C
2

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)

Charlottecharlottenburg answered 28/6, 2017 at 19:51 Comment(0)
W
0

In DTO we can't define property, but in view-model we define property means getter and setter. And if we pass data from controller to view and vice versa then use view-model. If we use repo pattern and pass data from service to controller then use DTO.

Warfourd answered 25/8, 2018 at 9:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.