什么是数据传输对象?

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


当前回答

DTO是一个愚蠢的对象——它只保存属性,有getter和setter,但没有任何其他重要的逻辑(除了一个compare()或equals()实现)。

通常MVC中的模型类(假设这里是。net MVC)是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是一个愚蠢的对象——它只保存属性,有getter和setter,但没有任何其他重要的逻辑(除了一个compare()或equals()实现)。

通常MVC中的模型类(假设这里是。net MVC)是dto,或者dto的集合/聚合

数据传输对象是用于封装数据并将数据从应用程序的一个子系统发送到另一个子系统的对象。

dto最常被n层应用程序中的服务层用于在自身和UI层之间传输数据。这样做的主要好处是减少了分布式应用程序中需要通过网络发送的数据量。它们还可以在MVC模式中创建很棒的模型。

dto的另一个用途是封装方法调用的参数。如果一个方法需要超过4个或5个参数,这可能很有用。

在使用DTO模式时,还可以使用DTO汇编程序。汇编程序用于从域对象创建dto,反之亦然。

从域对象转换到DTO并再转换回来可能是一个代价高昂的过程。如果您不是在创建分布式应用程序,那么您可能不会从这个模式中看到任何好处,Martin Fowler在这里解释道。

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

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

DTO可用于:

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

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

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