什么是数据传输对象?

在MVC模型类DTO,如果不是什么区别,我们需要两者吗?


当前回答

在MVC中,数据传输对象通常用于将域模型映射到最终由视图显示的更简单的对象。

从维基百科:

数据传输对象(DTO),以前称为值对象或VO 一种用于在软件应用程序之间传输数据的设计模式 子系统。dto通常与数据访问一起使用 对象从数据库检索数据。

其他回答

数据传输对象(DTO)描述了“承载数据的对象” (维基百科)或“用于封装数据的对象”, 并将它从应用程序的一个子系统发送到另一个子系统”(堆栈溢出 答案)。

To me the best answer to the question what is a DTO is that DTO's are simple objects that should not contain any business logic or methods implementation that would require testing. Normally your model (using the MVC pattern) are intelligent models, and they can contain a lot of/some methods that do some different operations for that model specifically (not business logic, this should be at the controllers). However, when you transfer data (eg. calling a REST (GET/POST/whatever) endpoint from somewhere, or consuming a webservice using SOA, etc...) you do not want to transmit the big sized object with code that is not necessary for the endpoint, will consume data, and slow down the transfer.

所有功劳都归里克-安德森所有

生产应用程序通常限制使用模型子集输入和返回的数据。这背后有很多原因,安全是一个主要原因。模型的子集通常被称为数据传输对象(DTO)、输入模型或视图模型。

DTO可用于:

防止over-posting。 隐藏客户端不应该查看的属性。 为了减少有效负载大小,省略一些属性。 扁平化包含嵌套对象的对象图。 扁平化的对象图对客户来说更方便。

DTO方法的实际实现,由rick - anderson在微软Web api最佳教程和实践中使用c#和asp.net Core 5:

数据传输对象背后的原理是创建新的数据对象,其中只包括特定数据事务所需的必要属性。

福利包括:

使数据传输更加安全 如果删除所有不必要的数据,则减少传输大小。

阅读更多信息:https://www.codenerd.co.za/what-is-data-transfer-objects

DTO的定义可以在Martin Fowler的网站上找到。dto用于将参数传递给方法并作为返回类型。很多人在UI中使用它们,但其他人从它们扩展域对象。