首先在实体框架代码中将bool值更改为enum

本文关键字:bool enum 实体 框架 代码 | 更新日期: 2023-09-27 18:06:40

我有代码优先生成的数据库。在它中,我有一个bool列在表中。该列需要更改为枚举。问题是表中已经有了数据,必须以某种方式进行转换。我有什么bool IsA: true/false我所需要的enum MyEnum:A, B, C, D我需要将IsA的值转换为true映射到A, false映射到B。我该怎么做呢?

首先在实体框架代码中将bool值更改为enum

您可以尝试在迁移类中执行此操作:

public partial class fromBool2Enum : DbMigration
{
    public override void Up()
    {
        //add new column:
        AddColumn("dbo.MyTable", "IsA_TEMP", c => c.Int());
        //transfer data to just created column
        Sql("Update dbo.MyTable set IsA_TEMP = case when IsA then 0 else 1 end");
        //0(i.e. A) and 1(i.e. B) is just example, correct it on your own, depending on enum's declaration
        //Drop old column
        DropColumn("dbo.MyTable", "IsA")
        //Rename new column to initial name
        Sql("EXEC sp_rename 'dbo.MyTable.IsA_TEMP', 'IsA', 'COLUMN'");            
    }
    public override void Down()
    {
         //corresponding reverse code...
    }       
}