如何创建自定义工具以在Visual Studio 2010中生成代码?

时间:2012-03-27 13:44:03

标签: c# visual-studio visual-studio-2010 auto-generate

我只想生成一个包含来自数据库表的属性的类。

如果我有类似以下的数据库表:

+-------------------+
| 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
}

3 个答案:

答案 0 :(得分:4)

您可以使用T4转换来完成工作。使用“添加新项目”和“文本模板”。

T4语言是一种使用C#代码生成C#代码的方法。大多数文本都直接解析为输出文件,新代码可以写在<##>标记内。该文件以包装的import和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 #>"; } 
    }

    <#
        }
    }

     #>

    }
}

} &lt;#@ output extension =“。cs”#&gt;

此模板将创建一个类TestClass,其中包含从数据库表TblBrandingKeyValues检索到的一组只读属性。

我会推荐这些T4 tutorials

答案 1 :(得分:0)

如果您想创建自己的自定义工具,最好查看System.CodeDom命名空间 其中包含生成代码所需的全部内容。当然,你必须编写生成类的算法。

以下链接中的更多信息:

http://msdn.microsoft.com/en-us/library/ms404245.aspx

请记住,.NET已经提供了许多完成相同工作的“内置”工具/命名空间(例如使用实体框架)

答案 2 :(得分:0)

使用T4 Templates。我通过这种方式生成了很多类。

相关问题