Entity Framework Tutorial Basics(32):Enum Support

追憶似水流年發表於2016-07-07

Enum in Entity Framework:

You can now have an Enum in Entity Framework 5.0 onwards. EF 5 should target .NET framework 4.5 in order to use Enum.

Enum can be created for the following data types:

  • Int16
  • Int32
  • Int64
  • Byte
  • SByte

You can create and use an Enum type in your entity data model in three ways:

  1. Convert an existing property of entity to Enum from EDM designer
  2. Add a new Enum from EDM designer
  3. Use an existing Enum type from different namespace

For the purposes of this demo, we have included the TeacherType integer column in the Teacher table of SchoolDB. TeacherType 1 is for permanent teachers, 2 is for contractor teachers, and 3 is for guest teachers.

1. Convert an existing property to Enum:

Next, we will see how to convert a TeacherType to an Enum.

First, right click on the TeacherType property of a Teacher entity and click 'Convert to Enum' in the context menu.

Entity Framework 5.0 Tutorial

It will open the 'Add Enum Type' dialog box where you can enter the 'Enum Type Name' and, select 'Underlying Type' and Enum member names. For example:

Entity Framework 5.0 Tutorial

After converting it to Enum, you can see TeacherType as Enum Type in the Model Browser, as shown below:

Entity Framework 5.0 Tutorial

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

Entity Framework 5.0 Tutorial

Now, you can use TeacherType Enum in CRUD operation using DBContext. For example:

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();
}

 

2. Add New Enum from Designer:

You can also add a new Enum by right clicking on EDM designer and selecting Add → Enum Type. It will open the same 'Add Enum Type' dialog box, where you can enter enum members.

Entity Framework 5.0 Tutorial

After creating an Enum Type you can change the type of the TeacherType property to the newly created TeacherType Enum from the property window.

3. 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. Then, you can assign this Enum type to any property of an entity from the property window.

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

相關文章