Entity Framework 5的新迁移功能是否完全支持枚举更改?

Cha*_*evy 11 migration enums entity-framework .net-4.5 entity-framework-5

假设我们有以下简单模型:

public class Car
{
    public int Year { get; set; }
    public string Make { get; set; }
    public string Model { get; set; }
    public CarType Type { get; set; }
}

public enum CarType
{
    Car, Truck
}
Run Code Online (Sandbox Code Playgroud)

实体框架在向Car数据库添加新对象时,会将CarType枚举值存储为整数.

如果我们CarType以整数值更改的方式更改枚举(更改顺序或添加/删除值),Entity Framework是否知道如何使用迁移正确处理数据迁移?


例如,假设我们添加了另一个值CarType:

public enum CarType
{
    Car, Truck, Van
}
Run Code Online (Sandbox Code Playgroud)

这对数据库中的现有数据没有实际影响.0仍然是Car,1现在仍然如此Truck.但如果我们改变顺序CarType,就像这样:

public enum CarType
{
    Car, Van, Truck
}
Run Code Online (Sandbox Code Playgroud)

1作为CarType指定的数据库记录Truck将是不正确的,因为1现在根据更新的模型Van.

Cha*_*evy 8

不,迁移完全支持枚举更改,因为它不更新数据库值以反映更改顺序,添加或删除等更改.

在保留订单的同时添加枚举值将不起作用.实际上,它甚至不会触发模型支持更改错误.

如果CarType枚举的顺序发生变化,那么数据库数据将无效.int保留原始值,但枚举结果将是错误的.

为了适应这种类型的更改,需要手动处理数据库数据.在此特定示例中,必须运行自定义SQL,以Type根据枚举更改更改列的值:

public partial class CarTypeChange : DbMigration
{
    public override void Up()
    {
        // 1 now refers to "VAN", and 2 now refers to "Truck"
        Sql("Update cars Set [Type] = 2 Where [Type] = 1");
    }

    public override void Down()
    {
        Sql("Update cars Set [Type] = 1 Where [Type] = 2");
    }
}
Run Code Online (Sandbox Code Playgroud)

附录:我已经提出了另一个与此相关的问题:处理实体框架5中的枚举更改