Complex DTO structure

六月ゝ 毕业季﹏ 提交于 2019-12-10 19:44:21

问题


I've read a lot about DTO's here on SO, in books and articles, but I'm not sure if I get it right.

We're using DTO's in our project so that they're almost just properties of Domain Objects. For that reason, we need to have a complex DTO structure. There're some classes extending one another, compositions, aggregate, etc. .

Question is more general.

Is it right to inherit a dto from another one or to have a reference on a dto in another dto?


回答1:


Is it right to inherit a DTO from another one

If they share common properties, then why not?

have a reference in a DTO to another DTO

There is definitely nothing wrong with this, consider the following:

public class UserDto
{
    public string Id { get; set; }
    public string Username { get; set; }
    public string Email { get; set; }
    public AddressDto Address { get; set; }
}

public class AddressDto
{
    public string AddressLine1 { get; set; }
    public string AddressLine2 { get; set; }
    public string City { get; set; }
}

Remember DTO's are simply dumb objects i.e. they have no behaviour (other than getting/setting their own data). The same rules apply to DTO's as they would for standard classes/objects from an architectural point of view, so there is no reason why you shouldn't be following the same principles if and when you can.




回答2:


DTO is for inter-layer communication.

I prefer simple DTOs because they are used mainly to tell the persistence layer, generally speaking Data Access Objects, what to store. If that's the case, don't go for complex DTOs.

If DTOs are complex (i.e. a DTO having another DTO as attribute), the complexity required for the DAO to store the data is greater. This conflicts the goal of DAO to be the way to decouple from storage technology.

So, if a DTO needs to address another DTO, just use string ids as attributes and keep a simple DAO for each DTO. Logic to handle interconnected DTOs should go to the Service Application or Business Object making use of the DAOs. This way, you increase reuse of the code.



来源:https://stackoverflow.com/questions/11667377/complex-dto-structure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!