0

在我的 N 层架构中,我有 DTO (AddressResponseDTO),其中有大约 20 个属性。当表示层向我的业务层请求(AddressRequestContext)特定搜索操作的响应时,我会将此 DTO(AddressResponseDTO)发送给 PL。

但情况并非总是如此。地址搜索请求将被更改有时我只需要发送它的 3 个属性(比如说城市、邮编和地址计数),有时它可能是 5 个。所以我仍然可以拥有具有 20 个属性的相同 DTO 来重用所有类型的搜索要求。

4

3 回答 3

2

As the OP states that sometimes only 3 of the properties are used, there can be several solutions:

  • Create a DTO with all the properties, and specifiy special values to show which properties aren't specificed (i.e. use nullables, or special values). This requires lots of checkings in the code.

  • Create a DTO with the 3 properties. Inherit a second DTO from this and add all the remaining properties. Your methods can receive the base class as parameter and check if a base or derived class is received. A simple check like if (myDto is DtoBase) ... will quickly show which properties have been sent with the DTO. (This will work only for increasing number of properties, in a hierarchy of inherited DTOs)

  • If there are more than one possible grouping of properties of interest, you can use a DTO class for each group and:

    • create a class which has this DTO as members. If you don't need them, leave them null. This way you can check each group with a simple if (containerDto.Dto1 != null)
    • define as many DTO parameters as you need for each case.

I don't like the "special value" way, because it requires more code and it's more error prone. Besides, it makes you (de)serialize more info than neccessary on many occasions.

于 2012-06-08T10:17:54.647 回答
2

编写具有 20 个属性的 DTO 并没有什么坏处。

但是,如果属性可以组合在一起,最好将相关属性组合成一个实体,就像您可以将 City、Zip 组合成一个地址一样。

于 2012-06-08T09:51:14.917 回答
1

是的,如果在这些情况下空属性或默认属性不会打扰您,您可以。从理论上讲,没有什么可以阻止您在所有情况下都使用一个类。

或者,您可以针对不同的用例创建多个 DTO 类定义。在这种情况下,我建议在这些类之间使用一些类层次结构。

我认为这取决于您以及您喜欢使用哪种方式的用例的复杂性。

于 2012-06-08T09:51:00.150 回答