Robert
Robert

Reputation: 1159

C# Enums and database tables

Is there a way to create an Enum, Collection or something similar that correlates with a database table, so every time I add a database row I would not have update my Enums in the codebase?...And strongly typed. Sorry, I had to throw that in there.

Upvotes: 2

Views: 788

Answers (2)

Chris Kooken
Chris Kooken

Reputation: 33870

T4 Templates, here is one i wrote this morning that builds a class and enum out of each record in a table.

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

     }    

}

Upvotes: 7

Oded
Oded

Reputation: 498992

You can use code generation that generates enums from specified lookup tables.

Upvotes: 1

Related Questions