5

我有一點困難讓Entity Framework 5枚舉映射到遷移中的整數列。下面的代碼是什麼樣子:保存枚舉時的值不正確

[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; } 
} 

遷移看起來是這樣的:

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"); 
    } 
} 

但是當我保存更改不會在數據庫中反映的。

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

數據庫:

---------------------------------------------------- 
|UserId | UserName | FullName | Status | 
---------------------------------------------------- 
|1  | new  | new  | 1  | 
---------------------------------------------------- 
+0

你的目標是.NET框架4,而不是.NET框架4.5? – Pawel

+0

我針對的是.NET Framework 4.5。 –

回答

4

這樣做的原因是,枚舉嵌套在一個類。實體框架不會發現嵌套類型。嘗試將枚舉移出課程並查看它是否有效。使用代碼第一種方法時

編輯

EF6現在支持嵌套類型(包括枚舉)。

+0

就是這樣。謝謝,我不知道這個限制。 –