有没有一种方法可以创建一个枚举、集合或与数据库表相关的类似东西,这样每次我添加一个数据库行时,我就不会在代码库中更新我的枚举?......并且是强类型的。抱歉,我不得不把它扔在那里。
最佳答案
T4 模板,这是我今天早上写的一个,它构建了一个类并枚举了表中的每条记录。
<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ output extension=".cs" #>
<#@ template language="C#v3.5" #>
<#@ output extension="CS" #>
<#@ assembly name="System.Data.dll" #>
<#@ assembly name="System.Xml.dll" #>
<#@ import namespace="System.Data" #>
<#@ import namespace="System.Data.SqlClient" #>
<#
string connectionString = @"Data Source=.\SQLEXPRESS;Initial Catalog=Portal;User Id=sa;Password=33321a;";
DataTable tables = new DataTable("Tables");
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = connection.CreateCommand();
command.CommandText = "select * from Rights order by name";
connection.Open();
tables.Load(command.ExecuteReader(CommandBehavior.CloseConnection));
}
#>
namespace <#Write(System.Runtime.Remoting.Messaging.CallContext.LogicalGetData("NamespaceHint").ToString());#>
{
public partial class RightsList
{
<# foreach (DataRow row in tables.Rows){
string name = row["Name"].ToString();
WriteLine("public string "+name+" { get; set; }");
}#>
}
public enum Rights
{
<# foreach (DataRow row in tables.Rows){
string name = row["Name"].ToString();
WriteLine(name+", ");
}#>
}
}
关于C# 枚举和数据库表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6232213/