Click here to Skip to main content
15,884,836 members
Articles / Programming Languages / C#

Creating Enums from Database Lookup Tables

Rate me:
Please Sign up or sign in to vote.
4.70/5 (9 votes)
3 Nov 2012CPOL3 min read 104.4K   3.5K   30  
Using T4 template an easy one-click synchronization between the enum in the code and the database values
<#@ template language="C#" debug="true" hostspecific="true"#>
<#@ include file="EF.Utility.CS.ttinclude"#>
<#@ import namespace="System.Data.SqlClient" #> 
<#
/*
 * Developer : Ronen Rabinovitz
 * Date : 06/07/2012
 * All code (c)2012 Ronen Rabinovitz, all rights reserved
 */


///////////////////////TEMPLATE PARAMETES////////////////////////////////////
//Database connection string
var connectionString = "data source=localhost;initial catalog=EF_Extention_Sample;integrated security=True;multipleactiveresultsets=True;";

//Enum value column name:
var enumDescriptionColumnName = "Enum_Description";

//Enum namespace
var enumNameSpace = "MyNamespace";

////////////////////////////////////////////////////////////////////////////


var fileManager = EntityFrameworkTemplateFileManager.Create(this);
var codeGenerationTools = new CodeGenerationTools(this);

//Open ADO connection
var connection = new SqlConnection(connectionString);
var command = connection.CreateCommand();
connection.Open();

command.CommandText = string.Format(@"SELECT DISTINCT t.NAME 
									FROM SYS.tables as t
									INNER JOIN SYS.columns AS c ON t.object_id = c.object_id
									AND c.name = '{0}'",enumDescriptionColumnName);
var tableReader = command.ExecuteReader();
var enumTables = new List<string>();
while (tableReader.Read())
{
	enumTables.Add(tableReader["NAME"].ToString());
}
connection.Close();

foreach (var tableName in enumTables)
{
	connection.Open();
	
	//Get the enum name
	var enumName = ConvertCaseString(tableName);
	fileManager.StartNewFile(enumName + "Enum.cs");

//Start write enum file:		
#>
namespace <#=enumNameSpace#>
{
	public enum <#=tableName#>_Enum
	{
	<#
	command.CommandText = string.Format("SELECT * FROM {0}",codeGenerationTools.Escape(tableName));
    var columnReader = command.ExecuteReader();
    while (columnReader.Read())
    {
		//Fill only the values that the field "enumDescriptionColumnName" have value
		if(!string.IsNullOrEmpty(columnReader[enumDescriptionColumnName].ToString().Trim()))
		{
	#>	<#=columnReader[enumDescriptionColumnName].ToString()#> = <#=columnReader[0].ToString()#>,
	<#	}
	}#>
}
}
<#
	connection.Close();
	
}
	fileManager.Process();
#>

<#+
		/// <summary>
        /// Converts the phrase to specified convention.
        /// </summary>
        /// <param name="phrase"></param>
        /// <param name="cases">The cases.</param>
        /// <returns>string</returns>
        public static string ConvertCaseString(string phrase)
        {
            phrase = phrase.ToLower().Replace("_", " ");
            string[] splittedPhrase = phrase.Split(' ', '-', '.');
            var sb = new StringBuilder();

            sb = new StringBuilder();

            foreach (String s in splittedPhrase)
            {
                char[] splittedPhraseChars = s.ToCharArray();
                if (splittedPhraseChars.Length > 0)
                {
                    splittedPhraseChars[0] = ((new String(splittedPhraseChars[0], 1)).ToUpper().ToCharArray())[0];
                }
                sb.Append(new String(splittedPhraseChars));
            }
            return sb.ToString();
        }
#>

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Chief Technology Officer Consist Systems
Israel Israel
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions