我应该为创建和更新使用不同的DTO吗? (CRUD) [英] Should I have different DTOs for Create and Update? (CRUD)

查看:413
本文介绍了我应该为创建和更新使用不同的DTO吗? (CRUD)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在设计一个对Person实体具有常规CRUD操作的Web API。

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

问题是我不知道如何设计DTO。

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

实体如下:

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

我确定DTO的成员应完全相同:

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; }
}

这对Update操作有意义,但是Create呢?
Id是由if操作本身创建的,因此DTO中的ID不符合语义。

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.

我应该创建2个不同的DTO,

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

最好的选择是什么?您有用于创建和更新的DTO吗?

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

推荐答案

您不需要其他DTO进行创建操作。您只需设置用于创建新对象的默认值(id = 0)。这将帮助您确定是否需要在数据库中创建对象。但是,如果将ID为零的DTO传递给用于create操作的方法,则永远不会遇到任何问题。

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.

这篇关于我应该为创建和更新使用不同的DTO吗? (CRUD)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆