Dynamically generate enumerations from database lookup table
How to automatically generate enumerations based on values stored in a database lookup table and keep the enumerations in sync with the database without manually modifying the code? This is a common question.
Code generation solutions
While it cannot be fully automated, code generation can provide a solution. Automatic generation of enumerations can be achieved by creating a separate project called "EnumeratedTypes" in the solution. This project acts as a console application, retrieving values from the database, constructing enumerations from those values, and saving them into a separate assembly.
In this code generation project, use the following code to define and populate dynamic enumerations:
<code class="language-csharp">// 创建动态程序集 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>
Other projects in the solution can reference this generated assembly, thereby accessing dynamic enumerations and providing IntelliSense support.
Post-build event automation
To ensure automatic generation of enumerations, the "EnumeratedTypes" project can add a post-build event. This event will run during the build process and generate the "MyEnums.dll" file.
Other notes
The above is the detailed content of How Can Enums Be Dynamically Generated from a Database Lookup Table?. For more information, please follow other related articles on the PHP Chinese website!