10
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?

Mr. Flibble
  • 26,564
  • 23
  • 69
  • 100

2 Answers2

15

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

bummi
  • 27,123
  • 14
  • 62
  • 101
Chris Lui
  • 341
  • 2
  • 9
2

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.

Corey Adler
  • 15,897
  • 18
  • 66
  • 80
  • 2
    Thanks. That looks quite painful :p I was hoping to be able to flick a flag in the config somewhere :) – Mr. Flibble Dec 16 '14 at 16:52
  • Yeah, I know. I cringed also, but I can't think of any other way to do it if you absolutely have to see strings in the database. – Corey Adler Dec 16 '14 at 18:47