实体框架5和Char Enums

Mik*_*ynn 3 enums entity-framework char entity-framework-5

实体框架5可以处理char枚举吗?我有一个int工作,但有一个char我得到下面的错误,其中数据库中的列是char(1).

The 'Gender' property on 'Division' could not be set to a 'String' value. You must set this property to a non-null value of type 'Gender'.

public enum Gender
{
    Male = 'M',
    Female = 'F'
}
Run Code Online (Sandbox Code Playgroud)

Paw*_*wel 7

您的枚举类型不是char类型,而是int类型.以下行将向您显示:

Console.WriteLine(typeof(Gender).GetEnumUnderlyingType());

System.Int32
Press any key to continue . . .
Run Code Online (Sandbox Code Playgroud)

枚举成员的值实际上分别为77和70:

Console.WriteLine((int)Gender.Male);
Console.WriteLine((int)Gender.Female);

77
70
Press any key to continue . . .
Run Code Online (Sandbox Code Playgroud)

C#/ VB.NET中唯一有效的基础类型的枚举类型是byte,sbyte,short,ushort,int,uint,long和ulong.如果您尝试将不在此列表中的基础类型放置如下:

public enum Gender : char
{ 
    Male = 'M', 
    Female = 'F' 
}
Run Code Online (Sandbox Code Playgroud)

您将看到以下编译错误:

error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected
Run Code Online (Sandbox Code Playgroud)

这是C#中枚举的理论.现在EF部分 - EF目前仅支持枚举的以下基础类型:Edm.Byte,Edm.SByte,Edm.Int16,Edm.Int32和Edm.Int64(Edm类型系统没有无符号类型).对于枚举属性,数据库中的相应列必须与属性的枚举类型的基础类型匹配(即,如果您的枚举属性的基础类型是Edm.Int32,那么该列应该是int类型).

在你的情况下 - 如果你真的想要使用你的枚举类型,你的数据库中的列应该是int类型.添加实体时,您应该期望在列中看到值70和77.