C#枚举和数据库表

本文关键字:数据库 枚举 | 更新日期: 2023-09-27 17:58:26

有没有一种方法可以创建与数据库表相关的枚举、集合或类似的东西,这样每次添加数据库行时,我都不会更新代码库中的枚举?。。。并且是强类型的。对不起,我不得不把它扔进去。

C#枚举和数据库表

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

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