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.
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.
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.
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.
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.
[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; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With