Shaping the Data
In this lesson, we're going to shape our returning data with the help of DTO.
Shaping data using DTO#
We got an error in the last lesson, and now you know the reason why. Our courses controller returns a category and when we will get category, it will have the list of courses which will have those categories again. This becomes a circular dependency which never ends. In this situation, rather than returning our original Entity which is causing the circular dependency, we will return Data Transfer Objects, DTO in short. DTOs are also termed as transfer objects. DTO is only used to pass data and does not contain any business logic.
Inside our API project, let's create a new folder called DTO. Inside, we need to create a new class which will return data instead of our Course entity; let's call it CourseDTO. Here, we can add everything we need to send to the frontend. Let's copy every thing from our Course Entity and paste it here. We need to send the Id which is not mentioned here. Let's write Guid ID followed by Get Set. We can get rid of the CategoryId and replace the Category type with string because we just want the Category name. Instead of Requirement, we need to make RequirementDto as well because we just need the name of the requirement, nothing else; and same goes for learnings. Inside DTO folder, let me create RequirementDto class first. It will only have Name property, so we can write public string Name followed by Get Set and that's it. Let's create a new class for Learnings as well. Let's call it LearningDto. This will have only Name property as well. We can use one for both of them actually, but we might need to add something else in the future, so let's keep it that way.
API/DTO/CourseDto.cs
Loading...