【问题标题】:How to create a custom tool to generate code in Visual Studio 2010?如何在 Visual Studio 2010 中创建自定义工具来生成代码?
【发布时间】:2012-03-27 13:44:02
【问题描述】:
我只是想使用来自数据库表的属性生成一个类。
如果我有如下的数据库表:
+-------------------+
| Id | Name |
+----+--------------+
| 1 + foo |
| 2 + hello.world |
| 3 + null |
+-------------------+
我想自动生成class,如下所示:
class MyTable {
public static int Foo = 1;
public static int HelloWorld = 1;
// null was omitted for Id = 3
}
【问题讨论】:
标签:
c#
visual-studio
visual-studio-2010
auto-generate
【解决方案1】:
您可以使用 T4 转换来完成这项工作。使用“添加新项目”和“文本模板”。
T4 语言是一种使用 C# 代码生成 C# 代码的方法。大多数文本直接解析到输出文件,新代码可以写入<# 和#> 标签内。该文件以包装好的导入和 using 语句开头,因此一个非常简单的模板可能类似于:
<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ import namespace="System.Data" #>
<#@ import namespace="System.Data.SqlClient" #>
<#@ assembly name="System.Data" #>
namespace Some.Namespace
{
public class TestClass
{
<#
using(var cnn = new SqlConnection(@"server=.\sqlexpress;Integrated Security=SSPI;Database=ApplicationManagement"))
{
cnn.Open();
var cmd = new SqlCommand("SELECT TextKey, TextValue FROM TblBrandingKeyValues WHERE BrandingIdentifier = 'Default'", cnn);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
var defaultText = reader.GetString(1);
var name = reader.GetString(0);
#>
public string <#= name #>
{
get { return "<#= defaultText #>"; }
}
<#
}
}
#>
}
}
}
此模板将创建一个类 TestClass,其中包含一组从数据库表 TblBrandingKeyValues 检索到的只读属性。
我会推荐这些T4 tutorials。