Store enum names in database with Entity Framework

entity-framework entity-framework-6

Question

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?

1
10
12/16/2014 4:25:29 PM

Popular Answer

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

15
7/26/2015 4:12:11 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow