Working with Enum in EF 6 DB-First

Enum is supported in Entity Framework 6 onwards. Enum can be created for the following data types:

  • Int16
  • Int32
  • Int64
  • Byte
  • SByte

Enum can be used in the following ways:

  1. Convert an existing property of an entity to enum type from EDM designer.
  2. Use an existing enum type from a different namespace.

Convert an Existing Property to Enum

Here, we will use the TeacherType integer column in the Teacher table. The enum value 1 is for permanent teachers, 2 is for contractor teachers, and 3 is for guest teachers.

Enum in Entity Framework 6

Now, to convert the TeacherType property to enum type from the designer, right click on the TeacherType property of a Teacher entity and click Convert to Enum in the context menu, as shown below.

Enum in Entity Framework 6

It will open the Add Enum Type dialog box. Enter the Enum Type Name and select int32 in the 'Underlying Type' dropdown. Enter the enum member names as shown below.

Enum in Entity Framework 6

This will add the TeacherType as Enum Type in the Model Browser, as shown below:

Enum in Entity Framework 6

Also, you can see that the type of the TeacherType property is converted to TeacherType Enum:

Enum in Entity Framework 6

Now, you can use the TeacherType Enum to assign a value of TeacherType instead of an integer value, as shown below.

using (var ctx = new SchoolDBEntities())
{
    Teacher tchr = new Teacher();
    tchr.TeacherName = "New Teacher";

    //assign enum value
    tchr.TeacherType = TeacherType.Permanent;

    ctx.Teachers.Add(tchr);

    ctx.SaveChanges();
}

Use an Existing Enum from a Different Namespace

If you already have an Enum type created in your code, then you can use that as a data type of any entity property.

To use an existing Enum type, right click on Designer → Add New → Enum Type. Enter the Enum Type Name in the dialog box. Do not enter the member as you already have that in your code.

Now, select the 'Reference external type' checkbox and enter the namespace of your existing enum and click OK. This will add the Enum type in the Model browser. Now, you can assign this Enum type to any appropriate property of any entity from the property window.

Note: Select the 'Set Flags attribute' if you want to use bitwise operators with your Enum.