Best method to store Enum in Database

前端 未结 10 1947
挽巷
挽巷 2020-12-12 12:42

What is the best method of storing an Enum in a Database using C# And Visual Studio and MySQL Data Connector.

I am going to be creating a new project with over 100 E

10条回答
  •  自闭症患者
    2020-12-12 13:12

    If you want a store of all of your enums values, you can try the below tables to store enums and their members, and the code snippet to add those values. I'd only do this at install time, however, since those values will never change until you recompile!

    DB Table:

       create table EnumStore (
        EnumKey int NOT NULL identity primary key,
        EnumName varchar(100)
    );
    GO
    
    create table EnumMember (
        EnumMemberKey int NOT NULL identity primary key,
        EnumKey int NOT NULL,
        EnumMemberValue int,
        EnumMemberName varchar(100)
    );
    GO
    --add code to create foreign key between tables, and index on EnumName, EnumMemberValue, and EnumMemberName
    

    C# Snippet:

    void StoreEnum() where T: Enum
        {
            Type enumToStore = typeof(T);
            string enumName = enumToStore.Name;
    
            int enumKey = DataAccessLayer.CreateEnum(enumName);
            foreach (int enumMemberValue in Enum.GetValues(enumToStore))
            {
                string enumMemberName = Enum.GetName(enumToStore, enumMemberValue);
                DataAccessLayer.AddEnumMember(enumKey, enumMemberValue, enumMemberName);
            }
        }
    

提交回复
热议问题