2011-06-03 41 views
2

有没有办法创建一个枚举,集合或类似的数据库表,所以每次我添加一个数据库行我不会更新我的代码库中的枚举?...并强烈键入。对不起,我不得不把它扔到那里。C#枚举和数据库表

回答

1

您可以使用从指定的查找表生成枚举的代码生成。

7

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+", "); 
     }#> 

    }  

}