问题
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 |
----------------------------------------------------
回答1:
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.
来源:https://stackoverflow.com/questions/14112436/incorrect-value-when-saving-enum