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

情到浓时终转凉″ 提交于 2019-12-08 08:12:24

问题


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?


回答1:


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.




回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!