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