Enum is supported in Entity Framework 6 onwards. Enum can be created for the following data types:
Enum can be used in the following ways:
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.
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.
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.
This will add the TeacherType
as Enum Type in the Model Browser, as shown below:
Also, you can see that the type of the TeacherType
property is converted to TeacherType
Enum:
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(); }
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.