Entity Framework Enum Code First Lookup Table

In this tutorial you will learn how to create lookup tables using enums in entity framework (EF) with Code-first approach.

With EF support for enums, you can include lookup tables in the code in form of enums and also have them in the database for integrity.

Contents

This tutorial provides the information you need about:

What Is Enum In C# ?

Enum or Enumerations is used to declare a list of named integer constants. The enum is used to give a name to each constant so that the constant integer can be referred using its name.

Enumerations appear in your source code. These are things that affect program logic because you’re going to have conditional statements based on the state of some entity comparing it with some enum value. This enums represents numerical values which can get used in place of IDs in database tables.

Creating Enum

C# usually manages the IDs of enumeration for you.

As you version your code from one version to the next you want to make sure that those IDs remain consistent. To keep it consistent we assing values to each enum. Below is the code for StatusEnum we will be working on.

1 public enum StatusEnum
2 {
3     FullTime = 0,
4     PartTime = 1,
5     Casual = 2,
6     Contract = 3
7 }

Creating Lookup Table Class Using Code-First Approch

We will create another class named Status to represent our above enum as lookup table. Status class will act as a lookup table for our above StatusEnum. Here we use StatusEnum as datatype for our IDs to constrain the Status ID to just those values in the StatusEnum.

1 public class Status
2 {
3     public StatusEnum Id { get; set; }
4     public string Name { get; set; }
5 }

Define Foreign Key Constraint Using Code-First Conventions

Below is the Employee class that represent our Employee Table. Below code will create the Foreign Key relationship inside a Employee, and constrain the Status ID to just those values in the StatusEnum.

 1 public class Employee
 2 {
 3     public long Id { get; set; }
 4     public string FirstName { get; set; }
 5     public string LastName { get; set; }
 6 
 7     //Below code will create the Foreign Key relationship inside a Employee, and 
 8     //constrain the Status ID to just those values in the StatusEnum
 9     //Here StatusEnum will act as ID/Primary key for Status table 
10     //and will be seeded manually 
11     //Look context class for additional model builder configuration which disables 
12     //the identity for Status table and
13     //Also look seed method in configuration.cs file
14     public StatusEnum StatusId { get; set; }
15     public virtual Status Status { get; set; }
16     
17 
18 }

Disable Identity for Lookup Table IDs

When you’re backing enum with the database you want to control those IDs. We can disable the identity on our lookup Status table by confuguring the modelBuilder. By disabling the identity we will have control over the IDs we want to poplulate, which will be the enum values in our case.

 1 public class ApplicationContext:DbContext
 2 {
 3     public DbSet<Employee> Employees { get; set; }
 4     public DbSet<Status> Statuses { get; set; }
 5 
 6     protected override void OnModelCreating(DbModelBuilder modelBuilder)
 7     {
 8         base.OnModelCreating(modelBuilder);
 9 
10         modelBuilder.Entity<Status>()
11             .Property(s => s.Id)
12             .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
13     }
14 }

Seeding Enum into Lookup Table

In order to insert the enumeration values into the database we’re going to take advantage of the seed method. This is a method on the configuration class that was created whenever we enabled migrations for the first time. Let’s jump to the code, and see how we can create seed data for an enumeration.

 1 internal sealed class Configuration : DbMigrationsConfiguration<ApplicationContext>
 2 {
 3     public Configuration()
 4     {
 5         AutomaticMigrationsEnabled = false;
 6     }
 7 
 8     protected override void Seed(MigrationTutorial.Models.ApplicationContext context)
 9     {
10         //  This method will be called after migrating to the latest version.
11 
12         //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
13         //  to avoid creating duplicate seed data.
14 
15         context.Statuses.AddOrUpdate( 
16             x=> x.Id,
17             Enum.GetValues(typeof(StatusEnum))
18                 .OfType<StatusEnum>()
19                 .Select(x => new Status() { Id = x, Name=x.ToString() })
20                 .ToArray());
21     }
22 }

By using the above method for seeding we can eliminate mistakes and error occur in populating enums in our lookup table.

References

Entity Framework Enum Code First Lookup Table
Share this

Subscribe to Code with Shadman