Incorrect value when saving enum

流过昼夜 提交于 2020-01-24 05:05:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!