T4模板生成枚举

时间:2010-12-09 04:59:46

标签: linq-to-sql t4

我正在创建一个T4模板来生成我的数据库的枚举。 基本上,我想要与SubSonic相同的功能,例如Linq-to-SQL或Entity Framework 4的Product.Columns.ProductId。

非常感谢任何帮助。 谢谢。

2 个答案:

答案 0 :(得分:34)

我已根据自己的需要编写了一个将您选择的查找表转换为枚举的表: 将此代码放在 EnumGenerator.ttinclude 文件中:

<#@ 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 ? ",\r\n" : 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(@"(?:.+Services\s)");
        string path = Path.GetDirectoryName(Host.TemplateFile);
        return rx.Replace(path, string.Empty).Replace("\\", ".");
    }
#>

然后,只要您想要生成枚举,只需创建一个与 UserType.tt 等数据库表同名的 tt 文件,并将此代码放入:

<#@ include file="..\..\T4 Templates\EnumGenerator.ttinclude" #>

我的blog post现在提供了更高级的模板。

答案 1 :(得分:3)

Pascalize的替代实现:

private static string Pascalize(object value)
{
    if (value == null)
        return null;

    string result = value.ToString();

    if (string.IsNullOrWhiteSpace(result))
        return null;

    result = new String(result.Select(ch => ((ch >= '0' && ch <= '9' || ch >= 'a' && ch <= 'z') ? ch : ((ch >= 'A' && ch <= 'Z') ? ((char)((int)ch + (int)'a' - (int)'A')) : '-'))).ToArray());
    string[] words = result.Split(new [] {'-'}, StringSplitOptions.RemoveEmptyEntries);
    words = words.Select(w => ((w[0] >= 'a' && w[0] <= 'z') ? (w.Substring(0, 1).ToUpper() + w.Substring(1)) : w)).ToArray();
    result = words.Aggregate((st1, st2) => st1 + st2);
    if (result[0] >= '0' && result[0] <= '9')
        result = '_' + result;

    return result;
}

如果您的结果为null,我建议使用“Value”+ id 作为值。

必须将结果与之前的值进行比较,如果您创建了重复项(由于数据错误或省略了字符),您可以添加“_”结束。

E.g。

int value = Convert.ToInt32(reader[enumTable.ValueId]);
string name = Pascalize(reader[enumTable.ValueName].ToString());
if (string.IsNullOrWhiteSpace(name))
    name = "Value" + value;

while (result.Values.Where(v => v.Name == name).SingleOrDefault() != null)
    name += '_';