5

I'm having a little difficulty getting Entity Framework 5 Enums to map to an integer column in a migration. Here's what the code looks like:

[Table("UserProfile")]
public class UserProfile
{
    public enum StudentStatusType
    {
        Student = 1,
        Graduate = 2
    }

    [Key]
    public int UserId { get; set; }
    public string UserName { get; set; }
    public string FullName { get; set; }
    public StudentStatusType Status { get; set; }
}

The migration looks like this:

public partial class EnumTest : DbMigration
{
    public override void Up()
    {
        AddColumn("UserProfile", "Status", c => c.Int(nullable: false, defaultValue:1));
    }

    public override void Down()
    {
        DropColumn("UserProfile", "Status");
    }
}

However when I save changes it doesn't reflect them in the database.

var user = new UserProfile();
user.Status = UserProfile.StudentStatusType.Graduate;
user.FullName = "new";
user.UserName = "new";
users.UserProfiles.Add(user);
users.SaveChanges();

Database:

----------------------------------------------------
|UserId   |   UserName   |   FullName   |   Status |
----------------------------------------------------
|1        |   new        |   new        |   1      |
----------------------------------------------------
4

1 回答 1

4

The reason for this is that the enum is nested in a class. Entity Framework does not discover nested types. Try moving the enum out of the class and see if it works.

Edit

EF6 now supports nested types (including enums) when using Code First approach.

于 2013-01-03T14:24:37.620 回答