2011-06-03 42 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+", "); 
     }#> 

    }  

}