什么是数据传输对象?
在MVC模型类DTO,如果不是什么区别,我们需要两者吗?
什么是数据传输对象?
在MVC模型类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.
其他回答
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:
数据传输对象是用于封装数据并将数据从应用程序的一个子系统发送到另一个子系统的对象。
dto最常被n层应用程序中的服务层用于在自身和UI层之间传输数据。这样做的主要好处是减少了分布式应用程序中需要通过网络发送的数据量。它们还可以在MVC模式中创建很棒的模型。
dto的另一个用途是封装方法调用的参数。如果一个方法需要超过4个或5个参数,这可能很有用。
在使用DTO模式时,还可以使用DTO汇编程序。汇编程序用于从域对象创建dto,反之亦然。
从域对象转换到DTO并再转换回来可能是一个代价高昂的过程。如果您不是在创建分布式应用程序,那么您可能不会从这个模式中看到任何好处,Martin Fowler在这里解释道。
我会把DTO解释给我的孩子
我的儿子,数据传输对象(又名DTO) **用于封装我们从一个端点发送到另一个端点的数据。 使用DTO为系统中的端点定义输入和输出接口 在这种情况下,可以将系统看作端点的集合。端点可以是任何相互通信的东西(移动应用程序,web应用程序,后端API)。
在MVC中,数据传输对象通常用于将域模型映射到最终由视图显示的更简单的对象。
从维基百科:
数据传输对象(DTO),以前称为值对象或VO 一种用于在软件应用程序之间传输数据的设计模式 子系统。dto通常与数据访问一起使用 对象从数据库检索数据。