繁体   English   中英

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

[英]How to create a custom tool to generate code in Visual Studio 2010?

我只想生成一个包含来自Database表的属性的类

如果我有一个如下所示的数据库表:

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

您可以使用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 #>"; } 
    }

    <#
        }
    }

     #>

    }
}

} <#@ output extension =“。cs”#>

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

我会推荐这些T4教程

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

更多信息在以下链接:

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM