保存时,枚举值不正确 [英] Incorrect value when saving enum

查看:242
本文介绍了保存时,枚举值不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在得到实体框架5枚举映射到在迁移整数列有点困难。下面的代码是什么样子:

  [表(用户配置)] 
公共类用户配置
{
公共枚举StudentStatusType
{
学生= 1,
研究生= 2
}

[关键]
公众诠释用户ID {搞定;组; }
公共字符串用户名{获得;组; }
公共字符串全名{获得;组; }
公共StudentStatusType状态{搞定;组; }
}



迁移看起来是这样的:

 公共部分类EnumTest:DbMigration 
{
公共覆盖无效向上()
{
AddColumn(用户配置 ,状态,C = GT; c.Int(可空:假的,设置defaultValue:1));
}

公共覆盖无效向下()
{
DropColumn(用户配置,状态);
}
}



然而,当我保存更改它并不能反映他们。在数据库

  VAR用户=新用户配置(); 
user.Status = UserProfile.StudentStatusType.Graduate;
user.FullName =新;
user.UserName =新;
users.UserProfiles.Add(用户);
users.SaveChanges();



数据库:

  --------------------------------------------- ------- 
|用户ID |用户名|全名|状态|
---------------------------------------------- ------
| 1 |新|新| 1 |
---------------------------------------------- ------


解决方案

这样做的原因是该枚举嵌套在一个类。实体框架不会发现嵌套类型。尝试将枚举出之类的,看看它是否工作。



修改



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


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

解决方案

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.

这篇关于保存时,枚举值不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆