Best method to store Enum in Database Best method to store Enum in Database database database

Best method to store Enum in Database


    [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;        }    }


We store ours as ints or longs and then we can just cast 'em back and forth. Probably not the most robust solution, but that what we do.

we are using typed DataSets, so, for example:

enum BlockTreatmentType {    All = 0};// blockTreatmentType is an int propertyblockRow.blockTreatmentType = (int)BlockTreatmentType.All;BlockTreatmentType btt = (BlockTreatmentType)blockRow.blocktreatmenttype;


If you need store in DB string values of enum field, better do like show below.For example, it can be needed if you are using SQLite, which don`t support enum fields.

[Required]public string PhoneTypeAsString{    get    {        return this.PhoneType.ToString();    }    set    {        PhoneType = (PhoneTypes)Enum.Parse( typeof(PhoneTypes), value, true);    }}public PhoneTypes PhoneType{get; set;};public enum PhoneTypes{    Mobile = 0,    Home = 1,    Work = 2,    Fax = 3,    Other = 4}