Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 5 and Char Enums

Can entity framework 5 handle char enums? I have it working with an int, but with a char I get the error below where the column in the database is 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'
}
like image 213
Mike Flynn Avatar asked Feb 19 '23 07:02

Mike Flynn


1 Answers

Your enum type is not of char type but of int type. The following line will show you that:

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

System.Int32
Press any key to continue . . .

The values of your enum members are actually 77 and 70 respectively:

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

77
70
Press any key to continue . . .

The only valid underlying types of enum types in C#/VB.NET are byte, sbyte, short, ushort, int, uint, long and ulong. If you try putting an underlying type that is not on this list like this:

public enum Gender : char
{ 
    Male = 'M', 
    Female = 'F' 
}

You will see the following compilation error:

error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected

This is the theory behind enums in C#. Now the EF part - EF currently suports only the following underlying types for enums: Edm.Byte, Edm.SByte, Edm.Int16, Edm.Int32 and Edm.Int64 (the Edm type system does not have unsigned types). For enums properties the corresponding column in the database must match the underlying type of the enum type of the property (i.e. if your the underlying type of your enum property is Edm.Int32 then the column should be of int type).

In your case - if you really want to go with your enum type your column in the database should be of int type. You should expect to see values of 70 and 77 in the column when you add entities.

like image 105
Pawel Avatar answered Mar 03 '23 13:03

Pawel