Enum in Entity Framework:

Enum is supported in Entity Framework 5.0 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 different namespace.

Convert an Existing Property to Enum:

Here, we will use 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 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 'Underlying Type' dropdown. Enter enum member names as shown below.

Enum in Entity Framework 6

This will add the TeacherType as Enum Types 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 TeacherType Enum to assign a value of TeacherType instead of 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 Different Namespace:

If you already have 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 '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 'Set Flags attribute' if you want to use bitwise operators with your Enum.