Reputation: 39484
I am using Entity Framework 6, just release, and need to:
1 - Map a table column to an Enum;
2 - Map a lookup table (has two columns: Id and Name) to an Enum.
Is this possible in Entity Framework 6?
Thank you, Miguel
Upvotes: 14
Views: 12628
Reputation: 149
Run in a similar problem recently and was surprised by lack of info on the subject. I had a database first EF Mapping and wanted to map Lookup tables to Enums (so the Enums would be generated). Nowadays you would like to achieve described functionality utilizing Value Conversion with EF Core.
But the real thing is that you most likely do not need to do this in the first place. There are 2 scenarios:
I had the scenario 1, so I just went with using class objects and call DB for the values. If you really want to limit DB access - cache the values.
Upvotes: 0
Reputation: 31620
You typically don't map table to an enum type. You just define an enum type based on what you have in your lookup table and use it without including these tables in the model. For instance for the Northwind.Categories table:
ID Name Description
1 Beverages Soft drinks, coffees, teas, beers, and ales
2 Condiments Sweet and savory sauces, relishes, spreads, and seasonings
3 Confections Desserts, candies, and sweet breads
4 Dairy Products Cheeses
5 Grains/Cereals Breads, crackers, pasta, and cereal
6 Meat/Poultry Prepared meats
7 Produce Dried fruit and bean curd
8 Seafood Seaweed and fish
You would create the following enum type
public enum Categories
{
Beverages = 1,
Condiments = 2,
Confections = 3,
Dairy_Products = 4,
Grains_Cereals = 5,
Meat_Poultry = 6,
Produce = 7,
Seafood = 8,
}
(make sure that enum values correspond to the values in your database) and you would use it in your app without including the Categories table - i.e. you would use this enum type as the type of the properties that are foreign keys to the Categories table in the database. Alternatively - e.g. if you need descriptions - you would create an entity corresponding to the Categories table and use the enum (as defined above) as the key property type. Then again you would use the enum type for all properties that in the database are foreign keys to the Categories table.
Upvotes: 16