我如何根据数据库查找表中的值自动创建枚举并随后在 C# 中使用它的值(使用企业库数据层)?
例如,如果我在数据库中添加一个新的查找值,我不想在代码中手动添加额外的静态枚举值声明 - 我想让枚举与数据库保持同步。
有这样的事情吗?
我不想创建代码生成的静态枚举(根据 The Code Project 文章 Enum Code Generator - Generating enum code automatically from database look up tables ),我希望它是完全自动的。
最佳答案
我正在做这件事,但您需要进行某种代码生成才能使其正常工作。
在我的解决方案中,我添加了一个项目“EnumeratedTypes”。这是一个控制台应用程序,它从数据库中获取所有值并从中构造枚举。然后它将所有枚举保存到程序集中。
枚举生成代码是这样的:
// Get the current application domain for the current thread
AppDomain currentDomain = AppDomain.CurrentDomain;
// Create a dynamic assembly in the current application domain,
// and allow it to be executed and saved to disk.
AssemblyName name = new AssemblyName("MyEnums");
AssemblyBuilder assemblyBuilder = currentDomain.DefineDynamicAssembly(name,
AssemblyBuilderAccess.RunAndSave);
// Define a dynamic module in "MyEnums" assembly.
// For a single-module assembly, the module has the same name as the assembly.
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(name.Name,
name.Name + ".dll");
// Define a public enumeration with the name "MyEnum" and an underlying type of Integer.
EnumBuilder myEnum = moduleBuilder.DefineEnum("EnumeratedTypes.MyEnum",
TypeAttributes.Public, typeof(int));
// Get data from database
MyDataAdapter someAdapter = new MyDataAdapter();
MyDataSet.MyDataTable myData = myDataAdapter.GetMyData();
foreach (MyDataSet.MyDataRow row in myData.Rows)
{
myEnum.DefineLiteral(row.Name, row.Key);
}
// Create the enum
myEnum.CreateType();
// Finally, save the assembly
assemblyBuilder.Save(name.Name + ".dll");
我在解决方案中的其他项目引用了这个生成的程序集。因此,我可以在代码中使用动态枚举,完成智能感知。
然后,我添加了一个构建后事件,以便在构建此“EnumeratedTypes”项目后,它会自行运行并生成“MyEnums.dll”文件。
顺便说一句,它有助于更改项目的构建顺序,以便首先构建“EnumeratedTypes”。否则,一旦您开始使用动态生成的 .dll,如果 .dll 被删除,您将无法进行构建。 (先有鸡还是先有蛋的问题——解决方案中的其他项目需要此 .dll 才能正确构建,而在构建解决方案之前无法创建 .dll...)
我从 this msdn article 得到了上面的大部分代码.
希望这对您有所帮助!
关于c# - 根据数据库查找表中的值自动创建枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/725043/