Enum Support in Entity Framework

I’ve used Entity Framework 4 quite a bit. One of the big problems was the lack of enumeration support. If you wanted to use enumerations in EF4, you’d have to create some sort of constants table with a foreign key constraint. Then you could map your constant table values to an enum. It felt very “hacky”.

I was excited to see Enum support in Entity Framework but never got a chance to look at it. Until now. It’s very easy, especially with the code-first approach.

I added support for students to specify their city and state during registration in the PracticeTime application.

I want to “control the vocabulary” of the state. Meaning, it’s not a text box. Rather, they must choose a pre-defined value. This list is a great example of using an Enum type In my case, named States

public enum States
{
 AL,
 AK,
 AZ,
.....

There’s a gotcha here. What’s stored in the database isn’t the text value, it’s the integer value. So, any changes to the order of the values it will change the meaning of the stored values in the database.

First, I add the type to the viewmodels and database models. I’m using the ASP.NET MVC5 Identity and Roles model. So I just extend ApplicationUser to get the field into the database.

public class ApplicationUser : IdentityUser
{
   public States State { get; set; }

…..

I need to add the field and a select list to choose from for the two registration viewmodels:

  1. ExternalLoginConfirmationViewModel
  2. RegisterViewModel
public SelectList StateTypes
{
 get
 {
  List<NameValue> nv = new List<NameValue>();
  foreach (string stateName in Enum.GetNames(typeof(States)))
  {
   nv.Add(new NameValue() { Name = stateName, Value = stateName });
  }
  return new SelectList(nv, "Value", "Name");
 }
}
[Required]
public States State { get; set; }

Then, I just need to add update the Register.cshtml.

<div>
 @Html.LabelFor(m => m.State, new { @class = "col-md-2 control-label" })
 <div>
  @Html.DropDownListFor(m=>m.State, Model.StateTypes, new { @class = "form-control" })
 </div>
</div>

Lastly, I only need to update two AccountController methods:

  1. Register
  2. ExternalLoginConfirmation

These methods need to take the values from passed in viewmodel and add them to the new database model.

var user = new ApplicationUser()
{
 UserName = model.UserName, 
....
 City = model.City,
 State = model.State
};

My favorite part of all this is the Enum resolution of the values from post to correct States enum. I no longer have to inspect the value and find the correct Enum myself.

Key Points:

  • Enum support in Entity Framework simplifies constant lookup management
  • There’s a risk if anyone re-orders the Enum
  • MVC will auto-resolve the value to the Enum. Nice!