问题
I have a chat application backend built using Web Api where I am exposing several database entities directly to clients. I was wondering whether there is any positive points to map the entities to DTOs or should I continue exposing the entities as I am currently. Just to clarify I am not asking a DTO vs non-DTO general question but just advantages of using it in this scenario since most of the fields in the entities would probably be used by the client.
回答1:
Yes, you can expose your entities if this is a small application developed by one person and you only have few days to finish it.
If you intend to build an application that may grow up in the future, you should consider using DTO because Domain Entities is not optimal for representation of data. Domain Entities always have more or less, not exactly what you need on the client side.
You can use a tool called AutoMapper to map Domain Entities to DTO.
Some demo: http://www.codeproject.com/Articles/61629/AutoMapper
回答2:
Same advantage as in any other application. There's no specific advantage in your app. Using DTO's is essentially a decoupling exercise, segregating properties from methods. At the moment you are passing database objects. Doing that could mean you are passing more than required and exposing more than needed. You are also implying a great deal, what and how operations are carried out. There again what are you are going to get out of the effort of splitting things up?
来源:https://stackoverflow.com/questions/14314368/to-use-or-not-to-use-data-transfer-objectsdto-in-a-web-api-chat-application-ba