DTOs - bradleypeterson/timetracker GitHub Wiki
What They Are
The Data Transfer Objects (DTOs) are used to pass data between the server and client. They have all the same data members as the models, but they are not strictly coupled to the models, so a DTO can be modified as needed without changing the actual entity. For example, this project uses DTOs: /TimeCats.web/DTOs/CourseDTO.cs.
How They Work
When a DTO is created, the data is cloned from the model. Cloning is necessary here because any changes to the DTO should not affect the actual entity. Most of the fields can be cloned directly, but references to other entities are left null unless they are explicitly included. For example, a GroupDTO will not have a Project unless its WithProject method is called. This prevents cyclic reference issues when the object is converted to JSON. The DTO saves a reference to the model instance to make these methods work, but the [JsonIgnore] attribute on that field keeps it out of the JSON.
How They Are Used
The DTOs are pretty simple to use. In the controllers, we can work with the entities as normal, but when it comes to returning data, rather than passing an actual model instance into the Ok method, we create a DTO and pass that instead. For example, when returning a group, rather than return Ok(group); we would use return Ok(new GroupDTO(group));, and if we need to include the project, we would use return Ok(new GroupDTO(group).WithProject());.