使用ADO.NET实体框架的价值present在表生成枚举实体、框架、价值、ADO

2023-09-03 03:27:14 作者:惹不起滚

我的要求是基于价值present从数据库表中创建一个枚举。我使用ADO.NET实体框架模型(.edmx文件),可以在任何一个你帮我。

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.

推荐答案

这可能是一个更容易使用T4模板。 Here是入门一个真正的好文章

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

我下面的例子中使用直接SQL连接,但你可以看到你可以包括任何code和产生的任何输出你喜欢成为被编译到项目中的CS文件。你可以用一个枚举了通过您的Entituy框架模型和输出相应的检索对象的集合替换下面的ADO语法。

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.

创建与目录扩展.TT一个文件,你想将生成的枚举文件。如果你的名字XXXXX.tt然后叫一个文件XXXXX.cs会产生这样的文件,适当命名的TT文件。

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 :)

要知道,这个数据库调用将尽一切编辑TT文件的时间。

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() #>
    }
}

尝试改善这一点。而不是写至一个StringBuilder,输出每reader.Read的结果()直接输出。此外,我已经包括了尚不存在一个FixName方法,但你可能需要一个拿出空格或非法字符。

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.