Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best method to store Enum in Database

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 Enums, and majority of them will have to be stored in the database. Creating converters for each one would be a long winded process therefore I'm wondering if visual studio or someone has any methods for this that I haven't heard off.

like image 236
Michal Ciechan Avatar asked Apr 15 '10 15:04

Michal Ciechan


People also ask

How is enum stored in database?

By default, when an enum is a part of an entity, JPA maps its values into numbers using the ordinal() method. What it means is that without customizations JPA stores enum value as numbers. These numbers are associated with the order in which you define values in the enum.

Should you store enums in database?

By keeping the enum in your database, and adding a foreign key on the table that contains an enum value you ensure that no code ever enters incorrect values for that column. This helps your data integrity and is the most obvious reason IMO you should have tables for enums.

Where should I store enum?

If the enum is only used within one class, it should be placed within that class, but if the enum is used between two or more classes, it ought to either be in it's own code file, or in a conglomerated code file that contains all the enum for a particular assembly.

How do I store multiple enums in a database?

You can use the '|' (bitwise OR ) operator to mask multiple roles together in a single 64-bit integer, which you can store in the database in an integer field (a bigint ). RoleEnum userRoles = RoleEnum. User | RoleEnum.


1 Answers

    [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;         }     } 
like image 114
Joao Leme Avatar answered Oct 08 '22 13:10

Joao Leme