Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is interpreted an enum type with EF Code First

Here is a model:

Public class Person
{
    [Key]
    Public int PersonId { get; set: }
    Public int Age { get; set; }
    Public ColorEnum FavoriteColor { get; set; }
}

Public Enum ColorEnum
{
    Red = 1,
    Green = 2,
    Blue = 3
}

Is it possible for Entity Framework Code First to use the Person model to generate the corresponding table? What about the ColorEnum type?

Thanks

like image 508
Bronzato Avatar asked Feb 23 '12 18:02

Bronzato


People also ask

What is enum in Entity Framework?

In Entity Framework, this feature will allow you to define a property on a domain class that is an enum type and map it to a database column of an integer type. Entity Framework will then convert the database value to and from the relevant enum as it queries and saves data.

How do you define enum data type?

Enumeration or Enum in C is a special kind of data type defined by the user. It consists of constant integrals or integers that are given names by a user. The use of enum in C to name the integer values makes the entire program easy to learn, understand, and maintain by the same or even different programmer.

How do you read enum value?

Get the value of an Enum To get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.

How does an enum work?

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.


1 Answers

EF 4.3 doesn't support Enums. But is has been announced that Enum support is coming with EF 5, which is due out alongside .NET 4.5. To handle enums with Code-First currently you'll do something like the following:

Public class Person
{
    [Key]
    Public int PersonId { get; set: }
    Public int Age { get; set; }

    public int FavoriteColorValue{ get; set;}
    [NotMapped]
    Public ColorEnum FavoriteColor 
    { 
        get{ return (ColorEnum)FavoriteColorValue; } 
        set{ FavoriteColorValue = (int)value; } 
    }
}

Public Enum ColorEnum
{
    Red = 1,
    Green = 2,
    Blue = 3
}
like image 171
Sorax Avatar answered Oct 08 '22 15:10

Sorax