简体   繁体   中英

When do we need to create a new custom DTO?

I had an Entity named User that can have many services (Entity Service) and I have two actions one of them with the name GetUser() and the other with name GetUserServices()

  • GetUser(): fetch the user and return an Custom DTO with name UserDto
public class UserDto
{
public int Id {get;set;}
public string Username {get;set;}
} 
  • GetUserServices(): fetch the user and its services ids, let's say at some point I want to return on this function these properties [UserId, Username, ServicesIds] my question is should I modify the UserDto by adding ServicesId property [1] or create another Custom DTO [2]?

  1. If I go with the solution [1] means that GetUser() will return a JSON object with empty ServicesId property and that's will lead to bad UX
  2. If I go with the solution [2] that will lead to create for each action I had, a custom DTO depends on the shape of data returned, and also I'll struggle with figure out the name for each created custom DTO.

You can use either ways. If you use separate DTO per operation - it's a lot of code writing (and time spending). I prefer to use one DTO for similar operations as long as they are readable and flexible and create additional if needed.

For more information have a look in this doc.You can find here some basic principles, pros and cons of DTO.

https://docs.microsoft.com/en-us/aspnet/web-api/overview/data/using-web-api-with-entity-framework/part-5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM