EF5 Code First Enums and Lookup Tables

Jerad Rose picture Jerad Rose · Jun 23, 2012 · Viewed 15.8k times · Source

I'd like to define an enum for EF5 to use, and a corresponding lookup table. I know EF5 now supports enums, but out-of-the-box, it seems it only supports this at the object level, and does not by default add a table for these lookup values.

For example, I have a User entity:

public class User
{
    int Id { get; set; }
    string Name { get; set; }
    UserType UserType { get; set; }
}

And a UserType enum:

public enum UserType
{
    Member = 1,
    Moderator = 2,
    Administrator = 3
}

I would like for database generation to create a table, something like:

create table UserType
(
    Id int,
    Name nvarchar(max)
)

Is this possible?

Answer

Tim Abell picture Tim Abell · Oct 23, 2014

Here's a nuget package I made earlier that generates lookup tables and applies foreign keys, and keeps the lookup table rows in sync with the enum:

https://www.nuget.org/packages/ef-enum-to-lookup

Add that to your project and call the Apply method.

Documentation on github: https://github.com/timabell/ef-enum-to-lookup