[英]How to create a custom tool to generate code in Visual Studio 2010?
I simply want to generate a class with attributes that comes from a Database table . 我只想生成一个包含来自Database表的属性的类 。
If I have a Database table like the following: 如果我有一个如下所示的数据库表:
+-------------------+
| Id | Name |
+----+--------------+
| 1 + foo |
| 2 + hello.world |
| 3 + null |
+-------------------+
I would like to auto-generate a class
that will looks like the following: 我想自动生成一
class
是将如下所示:
class MyTable {
public static int Foo = 1;
public static int HelloWorld = 1;
// null was omitted for Id = 3
}
You could use a T4 transformation to do the work. 您可以使用T4转换来完成工作。 Use "Add new item" and "Text template".
使用“添加新项目”和“文本模板”。
The T4 language is a way to use C# code to genarate C# code. T4语言是一种使用C#代码生成C#代码的方法。 Most text is parsed directly to the output file, and new code can be written inside
<#
and #>
tags. 大多数文本都直接解析为输出文件,新代码可以写在
<#
和#>
标记内。 The file starts with wrapped imports and using statements, so a very simple template could be something like: 该文件以包装的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" #> } <#@ output extension =“。cs”#>
This template would create a class TestClass
with a set of read only properties retrieved from database table TblBrandingKeyValues
. 此模板将创建一个类
TestClass
, TestClass
包含从数据库表TblBrandingKeyValues
检索的一组只读属性。
I would recommend these T4 tutorials . 我会推荐这些T4教程 。
if you want to create your own custom tool you better look at the System.CodeDom
Namespace which contains all you need for generating code. 如果要创建自己的自定义工具,最好查看
System.CodeDom
命名空间,其中包含生成代码所需的全部内容。 Of course you have to code the algorithm that generate the class. 当然,您必须编写生成类的算法。
more info at the below link: 更多信息在以下链接:
http://msdn.microsoft.com/en-us/library/ms404245.aspx http://msdn.microsoft.com/en-us/library/ms404245.aspx
Bear in mind anyway that .NET already offers lots of "build-in" tool/namespace that does exactly the same job (for example using Entity Framework) 请记住,.NET已经提供了许多完成相同工作的“内置”工具/命名空间(例如使用实体框架)
Use T4 Templates . 使用T4模板 。 I generate lots of classes that way.
我通过这种方式生成了很多类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.