Using C# and the Enterprise Library Data Access Layer (ELD) to automatically create enumerations for database lookup values
This article describes how to leverage the Enterprise Library Data Access Layer (ELD) to automatically create an enumeration from values stored in a database lookup table.
Dynamic generation of enumeration assembly
Create a separate console application project within your solution. This project is responsible for generating the enumeration assembly. Define a EnumBuilder
and use MyDataAdapter
and MyDataSet
to retrieve data from the database. Create an enumeration literal for each row in the database, add them to EnumBuilder
and finally create the enumeration. Save the generated assembly to the desired location.
Sample code:
<code class="language-csharp">// 获取当前应用程序域。 AppDomain currentDomain = AppDomain.CurrentDomain; // 创建一个动态程序集。 AssemblyName name = new AssemblyName("MyEnums"); AssemblyBuilder assemblyBuilder = currentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndSave); // 定义一个动态模块。 ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(name.Name, name.Name + ".dll"); // 定义一个枚举。 EnumBuilder myEnum = moduleBuilder.DefineEnum("EnumeratedTypes.MyEnum", TypeAttributes.Public, typeof(int)); // 从数据库获取数据。 MyDataAdapter someAdapter = new MyDataAdapter(); MyDataSet.MyDataTable myData = myDataAdapter.GetMyData(); foreach (MyDataSet.MyDataRow row in myData.Rows) { myEnum.DefineLiteral(row.Name, row.Key); } // 创建枚举。 myEnum.CreateType(); // 保存程序集。 assemblyBuilder.Save(name.Name + ".dll");</code>
Add a reference to the generated assembly
Reference dynamically generated assemblies in other projects in the solution. This will allow you to use enumerations defined in the generated assembly and include IntelliSense functionality.
Configure post-build events
Add a post-build event in the EnumeratedTypes
project. This event will start the project and generate MyEnums.dll
files after every build.
Other notes
Configure the build order of projects so that EnumeratedTypes
projects build first. This will prevent any dependency issues related to the generated assembly.
By following these steps, you can automatically create enumerations based on values from a database lookup table, ensuring your enumerations stay in sync with the database without the need for manual updates.
The above is the detailed content of How Can I Automatically Generate C# Enums from Database Lookup Values Using Enterprise Library Data Access?. For more information, please follow other related articles on the PHP Chinese website!