Generate Enum from Values present in a table using ADO.NET Entity framework

前端 未结 2 593
清酒与你
清酒与你 2021-01-04 23:02

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.

2条回答
  •  余生分开走
    2021-01-04 23:24

    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.

提交回复
热议问题