Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store enum names in database with Entity Framework

public enum Currency
  {
     EUR = 1,
     USD = 2,
     GBP = 3
   }

Let's say I have an enum as shown above. If I were to use this using Entity Framework (code first) then the int values will be stored in the database. No lookup table is stored nor the string names of the enum values, which makes it difficult to read the database data directly.

Is there a way to get EF to create a lookup table for enums?

like image 479
Mr. Flibble Avatar asked Dec 16 '14 16:12

Mr. Flibble


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.

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.

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.

What is enum in Entity Framework?

In Entity Framework, this feature will allow you to define a property on a domain class that is an enum type and map it to a database column of an integer type. Entity Framework will then convert the database value to and from the relevant enum as it queries and saves data.


2 Answers

You may try something like this which is easier...

public enum Currency
{
    EUR = 1,
    USD = 2,
    GBP = 3
}

public class YourClassName
{
    [Column("Currency")]
    public string CurrencyString
    {
        get { return Currency.ToString(); }
        private set { Currency = EnumExtensions.ParseEnum<Currency>(value); }
    }

    [NotMapped]
    public Currency Currency;
}

public class EnumExtensions
{
    public static T ParseEnum<T>(string value)
    {
        return (T)Enum.Parse(typeof(T), value, true);
    }
}

source: example by Bryan Hogan

like image 182
Chris Lui Avatar answered Oct 14 '22 06:10

Chris Lui


Yes there is. You'll have to add the table to your configuration, and then make sure to seed the values that you want into the table using reflection. Afterwards, just create the FK relation between the lookup table and any tables that you're using your enums on, and you should be set.

There's a good coding example of this in this post. That might help you get started.

like image 39
Corey Adler Avatar answered Oct 14 '22 05:10

Corey Adler