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
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.
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.
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.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With