Enums or Tables?

后端 未结 9 893
天命终不由人
天命终不由人 2021-02-06 08:38

I am making this a community wiki, as I would appreciate people\'s approach and not necessarily an answer.

I am in the situation where I have a lot of lookup type data

相关标签:
9条回答
  • 2021-02-06 09:11

    Use both enum(for code) and DB texts- for GUI presentation.

    So, if you will always have 3 option use an enum LowSalary, MiddleSalary and HighSalary, store your texts in the DB and switch your texts in the GUI corresponding to your property enum value.

    0 讨论(0)
  • 2021-02-06 09:13

    For static items I use Enum with [Description()] attribute for each element. And T4 template to regenerate enum with descriptions on build (or whenever you want)

    public enum EnumSalary
        {
            [Description("0 - 25K")] Low,
            [Description("25K - 100K")] Mid,
            [Description("100K+")] High
        }
    

    And use it like

    string str = EnumSalary.Mid.Description()
    

    P.S. also created extension for System.Enum

    public static string Description(this Enum value) {
        FieldInfo fi = value.GetType().GetField(value.ToString());
        var attributes = (DescriptionAttribute[]) fi.GetCustomAttributes(typeof(DescriptionAttribute), false );
        return attributes.Length > 0 ? attributes[0].Description : value.ToString();
    }
    

    and reverse to create enum by description

    public static TEnum ToDescriptionEnum<TEnum>(this string description)
    {
        Type enumType = typeof(TEnum);
        foreach (string name in Enum.GetNames(enumType))
        {
            var enValue = Enum.Parse(enumType, name);
            if (Description((Enum)enValue).Equals(description)) {
                return (TEnum) enValue;
            }
        }
        throw new TargetException("The string is not a description or value of the specified enum.");
    }
    
    0 讨论(0)
  • 2021-02-06 09:18

    Use both, And you should investigate the CodeDOM. using this you can write code generation routines that allow the compilation process to automatically generate an assembly or class with these enums in it, by reading the database. This way you get to let the database drive, but you are not making calls to the database everytime you access an instance of the enum...

    0 讨论(0)
提交回复
热议问题