生成枚举的 T4 模板 [英] T4 template to Generate Enums
问题描述
我正在考虑创建一个 T4 模板来生成我的数据库的枚举.本质上,我想要与 SubSonic 相同的功能,例如用于 Linq-to-SQL 或实体框架 4 的 Product.Columns.ProductId.
I'm looking at creating a T4 template to generate enums of my database. Essentially, I want the same feature as SubSonic e.g. Product.Columns.ProductId for Linq-to-SQL or Entity Framework 4.
任何帮助将不胜感激.谢谢.
Any help would be much appreciated. thanks.
推荐答案
我已经根据我的需要编写了一个将您选择的查找表转换为枚举的方案:将此代码放在 EnumGenerator.ttinclude 文件中:
I have written one for my needs that converts a lookup table of your choice to an enum: Put this code inside an EnumGenerator.ttinclude file:
<#@ template debug="true" hostSpecific="true" #>
<#@ output extension=".generated.cs" #>
<#@ Assembly Name="System.Data" #>
<#@ import namespace="System.Data" #>
<#@ import namespace="System.Data.SqlClient" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Text.RegularExpressions" #>
<#
string tableName = Path.GetFileNameWithoutExtension(Host.TemplateFile);
string path = Path.GetDirectoryName(Host.TemplateFile);
string columnId = tableName + "ID";
string columnName = "Name";
string connectionString = "data source=.;initial catalog=DBName;integrated security=SSPI";
#>
using System;
using System.CodeDom.Compiler;
namespace Services.<#= GetSubNamespace() #>
{
/// <summary>
/// <#= tableName #> auto generated enumeration
/// </summary>
[GeneratedCode("TextTemplatingFileGenerator", "10")]
public enum <#= tableName #>
{
<#
SqlConnection conn = new SqlConnection(connectionString);
string command = string.Format("select {0}, {1} from {2} order by {0}", columnId, columnName, tableName);
SqlCommand comm = new SqlCommand(command, conn);
conn.Open();
SqlDataReader reader = comm.ExecuteReader();
bool loop = reader.Read();
while(loop)
{
#> /// <summary>
/// <#= reader[columnName] #> configuration setting.
/// </summary>
<#= Pascalize(reader[columnName]) #> = <#= reader[columnId] #><# loop = reader.Read(); #><#= loop ? ",
" : string.Empty #>
<#
}
#> }
}
<#+
private string Pascalize(object value)
{
Regex rx = new Regex(@"(?:[^a-zA-Z0-9]*)(?<first>[a-zA-Z0-9])(?<reminder>[a-zA-Z0-9]*)(?:[^a-zA-Z0-9]*)");
return rx.Replace(value.ToString(), m => m.Groups["first"].ToString().ToUpper() + m.Groups["reminder"].ToString().ToLower());
}
private string GetSubNamespace()
{
Regex rx = new Regex(@"(?:.+Servicess)");
string path = Path.GetDirectoryName(Host.TemplateFile);
return rx.Replace(path, string.Empty).Replace("\", ".");
}
#>
然后,每当您想要生成枚举时,只需创建一个与数据库表同名的 tt 文件,例如 UserType.tt 并将此代码放入:
Then whenever you'd like an enum to be generated, just create a tt file with the same name as database table like UserType.tt and put this code in:
<#@ include file="....T4 TemplatesEnumGenerator.ttinclude" #>
我的博文.
这篇关于生成枚举的 T4 模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!