how to map enum with database id

This question already has an answer here:

  • Cast int to enum in C# 21 answers
  • Enum ToString with user friendly strings 19 answers

  • 你并不需要任何特别的东西,你可以将你从数据库中得到的整数转换为你的枚举:

    int valueFromDB = 4;
    Days enumValue = (Days)valueFromDB;
    

    I would not suggest this approach. You need a look-up table for days. For instance

    create table Days(
     DaysID INT PRIMARY KEY,
     Name VARCHAR(20))
    

    All other tables will have a foreign key column of DaysID. The reason why I suggest against your approach is because your limiting yourself to hard coded values that may change.

    If needed you can load your Days table into a List<KeyValuePair<int, string>> . If you leave as is, no one looking at the database will know ways DaysID 1, 2, 3, 4, etc represents.

    I hope this helps.


    Use below extension method to wordify your enum

    /// <summary>
    /// Get the whilespace separated values of an enum
    /// </summary>
    /// <param name="en"></param>
    /// <returns></returns>
    public static string ToEnumWordify(this Enum en)
    {
        Type type = en.GetType();
        MemberInfo[] memInfo = type.GetMember(en.ToString());
        string pascalCaseString = memInfo[0].Name;
        Regex r = new Regex("(?<=[a-z])(?<x>[A-Z])|(?<=.)(?<x>[A-Z])(?=[a-z])");
        return r.Replace(pascalCaseString, " ${x}");
    }
    

    Or you can supply Description to enum get it using below

    public enum Manufacturer
    {
        [DescriptionAttribute("I did")]
        Idid = 1,
        [DescriptionAttribute("Another company or person")]
        AnotherCompanyOrPerson = 2
    }
    
    /// <summary>
    /// Get the enum description value
    /// </summary>
    /// <param name="en"></param>
    /// <returns></returns>
    public static string ToEnumDescription(this Enum en) //ext method
    {
        Type type = en.GetType();
        MemberInfo[] memInfo = type.GetMember(en.ToString());
        if (memInfo != null && memInfo.Length > 0)
        {
            object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (attrs != null && attrs.Length > 0)
                return ((DescriptionAttribute)attrs[0]).Description;
        }
        return en.ToString();
    }
    
    链接地址: http://www.djcxy.com/p/22518.html

    上一篇: 将int转换为枚举的正确方法

    下一篇: 如何将枚举与数据库ID进行映射