如何使用EF Code First解释为枚举类型

时间:2012-02-23 18:28:12

标签: asp.net-mvc entity-framework

这是一个模型:

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
}

Entity Framework Code First是否可以使用Person模型生成相应的表?那么ColorEnum类型呢?

由于

1 个答案:

答案 0 :(得分:11)

EF 4.3不支持枚举。但是已经宣布Enum support is coming with EF 5,它将与.NET 4.5一起发布。要使用Code-First处理枚举,您现在可以执行以下操作:

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
}