views:

136

answers:

1

My requirement is to create an Enum based on values present in a table from DB. I am using ADO.NET Entity Framework model (.edmx file), Can any one of you help me out...

Thanks, Vinni

+3  A: 

It is probably a lot easier to use T4 templates. Here is a really good article on getting started

My example below uses a direct SQL Connection, but as you can see you can include any code and generate whatever output you like into a cs file that is compiled into your project. You could replace the ADO syntax below with an enumeration over a collection of objects retrieved via your Entituy Framework model and output accordingly.

Create a file with the extension .tt in the directory where you would like the enumeration file to be generated. If you name the file XXXXX.tt then a file called XXXXX.cs will be generated so, name the tt file appropriately.

Try something along these lines. You might need to experiment a little with the syntax and the output, but I'm not going to write it all for you or you won't learn anything :)

Just be aware, that this database call will be made every time you edit the tt file.

<#@ template language="C#" hostspecific="True" debug="True" #>
<#@ output extension="cs" #>
<#@ assembly name="System.Data" #>
<#@ import namespace="System.Data" #>
<#@ import namespace="System.Data.SqlClient" #>
<#
    SqlConnection sqlConn = new SqlConnection(@"Data Source=XXXX;Initial Catalog=XXXX; Integrated Security=True");
    sqlConn.Open();
#>
namespace AppropriateNamespace
{
public enum YourEnumName
{
    <#
    string sql = string.Format("SELECT Id, Name FROM YourTable ORDER BY Id");
    SqlCommand sqlComm = new SqlCommand(sql, sqlConn);
    IDataReader reader = sqlComm.ExecuteReader();

    System.Text.StringBuilder sb = new System.Text.StringBuilder();
    while (reader.Read())
    {
        sb.Append(FixName(reader["Name"].ToString()) + " = " + reader["Id"] + "," + Environment.NewLine + "\t\t");
    }
    reader.Close();
    sqlComm.Dispose();
    #>
<#= sb.ToString() #>
    }
}

Try improving on this. Rather than writing to a StringBuilder, output the results of each reader.Read() directly to the output. Also, I have included a FixName method that doesn't exist yet, but you might need that to take out spaces or illegal characters.

Daniel Dyson
I dont know wat are T4 template..
Vinni
I am currently looking for a helpful link
Daniel Dyson
Okay..Thanks...
Vinni
Let me know how you get on. I will Edit my answer based on your feedback to make it more helpful to others
Daniel Dyson
Thanks it worked for me..
Vinni
Good to hear. Would you be able to tag your question with the T4 tag?
Daniel Dyson