C# 枚举和数据库表

标签 c# database enums

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

最佳答案

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/

相关文章:

database - Tomcat JNDI 通过 SSH 连接数据库

c# - 简单比较枚举是否在枚举列表中

mysql - 数据库中的枚举

c# - 知道表单在 MVC 3 中是否有验证错误

c# - ListView 图标显示模糊 (C#)

sql-server - 我怎样才能得到没有外键约束的列表?

sql - 错误 : SubQuery returns more than one records

java - 接口(interface) Enum 的静态方法

c# - 使用 azure b2c 跳过密码重置时的电子邮件验证步骤

c# - 如何在 C# 中覆盖 WinForm UserControl 中的方法和事件?