Entity Framework Tutorial Basics(32):Enum Support
2016-07-07 10:40
288 查看
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:
Convert an existing property of entity to Enum from EDM designer
Add a new Enum from EDM designer
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.
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:
After converting it to Enum, you can see 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 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.
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.
相关文章推荐
- leetcode Reverse Words in a String
- 125种滤镜:GPUImage
- centos安装php扩展xdebug安装以及用kcachegrind系统分析
- MySQL NULL 值处理
- nginx常用配置
- 浏览器滚动条到底触发事件
- 通过Runtime机制,判断参数类型
- ios 数据存储方式
- 分布式文件系统(2)
- java 调用构造器就创建对象吗?
- 1011-K专题四
- 打开多链接的方法
- Android绘图三大基本类
- Django 中的Meta元类
- java Web读取图片显示
- 深入理解CSS弹性盒模型flex
- async & await 的前世今生(Updated)
- SQL SERVER 2008 下载地址&安装方法
- 分布式文件系统
- Fygon