我正在寻找使用一组约定(例如所有公共属性)从业务对象(类型定义,而不是映射数据)生成数据传输对象的最佳方法,并且可能可以配置以确定要走多深。
我意识到,对于许多 dto 与业务对象不相似的情况(例如将多个业务对象扁平化为单个数据传输对象时),这可能是不可能的,甚至是不可取的。
然而,就我而言,我的大部分数据传输对象与其业务对象非常相似(特别是用于更新数据的 DTO)。
我想知道是否有任何现有的代码生成工具(我正在寻找具有现有模板的特定解决方案,而不仅仅是像 CodeSmith 这样的通用代码生成工具)或动态程序集创建工具(例如在幕后使用 Reflection Emit)?或者,如果这是您之前做过的事情,我有兴趣听听您使用什么技术来帮助我在各种选项之间做出决定。
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.
发布评论
评论(3)
您可能会发现 AutoMapper 非常有用: http://www.codeplex.com/AutoMapper
编辑,回应 OP 评论:
T4 模板包含在 Visual Studio 中用于代码生成。这是一篇关于使用 T4 生成实体到 DTO 代码的文章:
http://weblogs.asp.net/cibrax/archive/2009/03/11/code- Generation-with-t4-an-entities-to -dto-example.aspx
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
在某种程度上,.NET 框架本身可以使用匿名类来做到这一点。
例如,使用 Linq to Objects(例如您的业务对象),您可以将结果集“投影”到匿名类(列表)中。
其主要缺点是现在它们不太可移植,但是使用 .NET 4.0 和动态类,我敢说您不需要使用第 3 方解决方案,我认为您将拥有框架本身的工具。
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.
我还推荐 T4模板。您可以使用反射来输入元数据,实际模板看起来类似于 asp 标记。这是VS内置的。
I would also recommend T4 Templates. You can use reflection to feed in metadata and the actual template looks similar to asp markup. This is built into VS.