DTO in Entity Framework
Im planning to implement an NTier design in EF 4. I know that the EF itself creates entities base on the tables it mapp开发者_JS百科ed in the Database. My question is, what is the use of DTO (Data Transfer Object) or is it really needed? It looks like it promotes redunduncy since you have to create another DTO entity for every entity the EFs generated. Please guide me. thanks..
DTO is data transfer object used to transfer only needed data between physical tiers (when tiers are in another processes or on another servers). If you need to expose only person's Name and Age you don't need to transfer her address, employment, children, etc. So you will create simple transport object which will contain only name and age.
EF will create entities which map database records to properties. EF entity can also be extended (by partial classes) to full domain object with custom computed properties and methods. Domain objects should not be exposed to different tier directly and that is another case where DTOs are used.
Edit:
The last situation where DTOs are used is optimization of cross boundary calls. If you have tiered application where one tier calls methods on another tier over process boundary you should minimize those calls because they decrease performance (are slow). To do that you can create special DTOs transferring complex data structures (several entities) to some master operation (facade) on remote tier which will further use data to execute multiple business operations.
DTO's are most helpful when you need to pass a portion of an entity or a few entities bundled together. Also, your Entities are actually tied to some entity context so when you pass an entity outside, they can execute the methods on it, change the data, etc. If you just want to pass an object outside, in this case you can benefit from using DTOs.
精彩评论