views:

55

answers:

2

I'm looking for the best approach for generating data transfer objects from business objects (the type definition, not mapping the data) using a set of conventions (e.g. all public properties), and possibly configurable to determine how deep to go.

I realize that this may not be possible or even desirable for many cases where the dto's don't resemble the business objects (such as when flattening a number of business objects into a single data transfer object).

However, in my case, a large percentage of my data transfer objects are very similar to their business objects (especially for the DTO's for updating the data).

I was wondering whether there are any existing code generation tools (I'm looking for specific solutions with existing templates, not just a general purpose code gen tool like CodeSmith), or dynamic assembly creation tools (e.g. using Reflection Emit under the covers)? Or if this is something you've done before I'd be interested to hear about what technique you used to help me decide between the various options.

+4  A: 

You are likely to find AutoMapper quite useful: http://www.codeplex.com/AutoMapper

Edit, in response to OP comment:

T4 templates is included in Visual Studio for code generation. Here is a post on entity-to-DTO code generation with T4:

http://weblogs.asp.net/cibrax/archive/2009/03/11/code-generation-with-t4-an-entities-to-dto-example.aspx

Jay
recent codeproject article may help others get up to speed: http://www.codeproject.com/KB/library/AutoMapper.aspx
James Manning
pretty cool framework
Benny
Thanks for your answers, but from what I can gather, AutoMapper requires that you have a Dto object to map onto already. I'm looking for a tool to generate the Dto type for me, so that I can then use AutoMapper (or another method) to map from the business object to the Dto.
Teevus
Teevus, see edit re: T4 templates for code generation.
Jay
A: 

Well to some extent the .NET framework itself can do this with anonymous classes.

For example with Linq to Objects (your business objects for example) you can "project" your result sets into (lists of) anonymous classes.

The main shortcoming of this is right now they would not be very portable, however with .NET 4.0 and dynamic classes I daresay you would not need to use a 3rd party solution, I reckon you would have the tools with the framework itself.

Tim Jarvis
Sounds promising, although the dynamically created objects would need to be serializable to be transported over the wire, and one would need to have enough control over the xml produced to be able to deserialize into equivalent (but different) types on the other end of the wire. I'll post further comments on this once I've had a chance to investigate further.
Teevus