Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I have different DTOs for Create and Update? (CRUD) [closed]

I'm designing a Web API with the usual CRUD operations on a Person entity.

The problem is that I don't know how to design the DTOs.

The entity is as follows:

public class Person 
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

I have determined that the DTO should have the very same members:

public class PersonDto 
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age{ get; set; }
}

That makes sense for the Update operation, but what about Create? The Id is create by the Create operation ifself, so having an Id in the DTO doesn't fit the semantics.

Should I create 2 different DTOs, one with Id and another without Id?

What's the best option? Do you have different DTOs for Create and Update?

like image 340
SuperJMN Avatar asked Sep 06 '17 10:09

SuperJMN


People also ask

When should you use DTOs?

A DTO is helpful whenever you need to group values in ad hoc structures for passing data around. From a pure design perspective, DTOs are a solution really close to perfection. DTOs help to further decouple presentation from the service layer and the domain model.

What are DTOs in API?

As stated in the general design considerations, in most cases the DTO pattern should be implemented using an API Resource class representing the public data model exposed through the API and a custom data provider. In such cases, the class marked with #[ApiResource] will act as a DTO.

Is DTO a good practice?

Transfering data using Dtos between "local" services is a good practice but have a huge overhead on your developer team. There is some facts: Clients should not see or interact with Entities ( Daos ). So you always need Dtos for transferig data to/from remote (out of the process).

What is DTO in Entity Framework?

A Data Transfer Object (commonly known as a DTO) is usually an instance of a POCO (plain old CLR object) class used as a container to encapsulate data and pass it from one layer of the application to another. You would typically find DTOs being used in the service layer to return data back to the presentation layer.


2 Answers

You do not need another DTO for create operation. You just set the default value(id=0) for creating a new object. This will help you for figuring out if the object is yet to be created in database in case you have to. Though, if you are passing your DTO with ID zero to methods meant for create operation, you would never face any problem.

like image 126
tech-y Avatar answered Sep 18 '22 08:09

tech-y


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 all operations and create additional if needed.

like image 20
Alex Zaitsev Avatar answered Sep 17 '22 08:09

Alex Zaitsev