我正在考虑创建一个 T4 模板,用于生成我的数据库的枚举。 实质上,我想要与 SubSonic 相同的功能,例如 Linq-to-SQL 或 Entity Framework 4 中的 Product.Columns.ProductId。
非常感谢任何帮助。
我正在考虑创建一个 T4 模板,用于生成我的数据库的枚举。 实质上,我想要与 SubSonic 相同的功能,例如 Linq-to-SQL 或 Entity Framework 4 中的 Product.Columns.ProductId。
非常感谢任何帮助。
我为自己的需要编写了一个将查找表转换为枚举类型的代码:
将以下代码放入 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("\\", ".");
}
#>
当你想要生成一个枚举类型时,只需创建一个与数据库表同名的tt文件,比如UserType.tt,并将以下代码放入其中:
<#@ include file="..\..\T4 Templates\EnumGenerator.ttinclude" #>
现在我的博客文章中提供了更加先进的模板。
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;
}
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 += '_';
(?:^|[^a-zA-Z]*)(?<first>[a-zA-Z])(?<reminder>[a-zA-Z0-9]*)(?:[^a-zA-Z0-9]*$)?
,它将适用于您提供的所有情况。尽管我不想支持单字母序列,但在末尾有非单词字符的情况下存在错误。因此,我还更新了上面答案中的正则表达式。 - Robert Koritnik