Why we should use Data Transfer Object?
- We Use DTO or Data Transfer objects for Decoupling our app from directly being connected to entity data model.
- DTO gives additional security and Flexibility in our code.
- We Can Change easily our object-relational mapping framework such as entity framework to any another framework.
What Are The Best Practices of using Data Transfer Object?
we must send DTO to our client side and receive DTO from our client side . Our Entity Data Model object Should Never be exposed to our client directly.
How can DTO be used in our MVC/Web Api 2 project ?
- Manually
- Using Automapper
Implementation :
our database Diagram, (I keep it as simple as possible)
step 1: Install auto-mapper from NuGet package manager
step 2: Add Entity Framework ( DB first/code first ) data Models .
(this will be covered in separate blog) , for simplicity I assume that you know how to implement EF 6 from a desired database.
step 3 : Entity Data Model will be like this,
Step 4:create DTO(data transfer object) from entity-framework entities
Step 5: Add MappingProfile.cs Class inside App_Start folder
Step 6: Add below code in Global.asax inside Application_Start() method
Step 7: Now you can apply conversation like this in your MVC controller/API controller
converting list of Entity object into list of DTO .
Converting single object