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?
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.
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.
来源:https://stackoverflow.com/questions/46073058/should-i-have-different-dtos-for-create-and-update-crud