Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incorrect value when saving enum

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      |
----------------------------------------------------
like image 579
Jeff the Bear Avatar asked Oct 06 '22 11:10

Jeff the Bear


1 Answers

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.

like image 185
Pawel Avatar answered Oct 10 '22 03:10

Pawel