gpt4 book ai didi

c# - 保存枚举时值不正确

转载 作者:太空狗 更新时间:2023-10-29 23:24:27 24 4
gpt4 key购买 nike

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

但是,当我保存更改时,它不会在数据库中反射(reflect)它们。

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 |
----------------------------------------------------

最佳答案

这样做的原因是枚举嵌套在一个类中。 Entity Framework 不发现嵌套类型。尝试将枚举移出类,看看它是否有效。

编辑

EF6 现在在使用 Code First 方法时支持嵌套类型(包括枚举)。

关于c# - 保存枚举时值不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14112436/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com