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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With