Best method to store Enum in Database

前端 未结 10 1961
挽巷
挽巷 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:22

        [Required]
        public virtual int PhoneTypeId
        {
            get
            {
                return (int)this.PhoneType;
            }
            set
            {
                PhoneType = (PhoneTypes)value;
            }
        }
        [EnumDataType(typeof(PhoneTypes))]
        public PhoneTypes PhoneType { get; set; }
    
    public enum PhoneTypes
    {
        Mobile = 0,
        Home = 1,
        Work = 2,
        Fax = 3,
        Other = 4
    }
    

    Works like a charm! No need to convert (int)Enum or (Enum)int in code. Just use the enum and ef code first will save the int for you. p.s.: "[EnumDataType(typeof(PhoneTypes))]" attribute is not required, just an extra if you want additional functionality.

    Alternatively you can do:

    [Required]
        public virtual int PhoneTypeId { get; set; }
        [EnumDataType(typeof(PhoneTypes))]
        public PhoneTypes PhoneType
        {
            get
            {
                return (PhoneTypes)this.PhoneTypeId;
            }
            set
            {
                this.PhoneTypeId = (int)value;
            }
        }
    

提交回复
热议问题