Miguel Moura
Miguel Moura

Reputation: 39484

Map Table Column to Enum and Lookup Table to Enum

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

Answers (2)

Egor Osaulenko
Egor Osaulenko

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:

  1. You have your Lookup table and Reverse Engineer it to Enum in your application. If you would add new row to the Lookup - you will have to rescaffold the Enum. This means you wont be able to use new entry without new deploy. Thats a no go.
  2. If Lookup remain unchanged - just write down the Enum in your code. But then - you don't need the lookup table in the first place.

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

Pawel
Pawel

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

Related Questions