2

我正在为我的项目进行数据迁移。但我有一个问题,例如:我有以下字段的 Book 表:

ID  Name   Color

1   Java    red

2   MVC     blue

3   .Net    blue

我尝试使用 Code First 技术将字段名称从“Color”更改为“BookColor”。但迁移后,表格如下所示:

ID  Name   BookColor

1   Java    null

2   MVC     null

3   .Net    null

我丢失了我的字段值。我怎样才能确保所有的价值都被转移了?

我正在使用带有 MVC3 的实体框架

编辑这是我的 DBMigration 类:

public partial class AddCreative : DbMigration
{

    public override void Up()
    {
        AddColumn("Authors", "Names", c => c.String(maxLength: 4000));
        DropColumn("Authors", "Name");
    }


    public override void Down()
    {
        AddColumn("Authors", "Name", c => c.String(maxLength: 4000));
        DropColumn("Authors", "Names");
    }
}

更改后我已更改NameNames (我在名称字段中丢失了数据)。

4

2 回答 2

6

我使用以下内容没有问题:

首先,设置迁移:

PM> Enable-Migrations
PM> Add-Migration RenameBookColorColumn

然后我们设置迁移类来执行重命名:

public class RenameBookColorColumn : DbMigration
{
    public override void Up()
    {
        this.RenameColumn("Books", "Color", "BookColor");
    }
    public override void Down()
    {
        this.RenameColumn("Books", "BookColor", "Color");
    }
}

接下来,调用 ,Update-Database以便我们可以执行更改:

PM> Update-Database -Verbose
Using NuGet project 'Example'.
Using StartUp project 'ExampleTest'.
Target database is: 'ExampleContext' (DataSource: .\SQLEXPRESS, Provider: System.Data.SqlClient, Origin: Convention).
Applying explicit migrations: [201207051400010_RenameBookColorColumn].
Applying explicit migration: 201207051400010_RenameBookColorColumn.
EXECUTE sp_rename @objname = N'Books.Color', @newname = N'BookColor',
@objtype = N'COLUMN' [Inserting migration history record]

瞧,它被重命名并保留了数据。

于 2012-07-05T14:27:08.417 回答
1

You can work around the limitation by using the following code.

public partial class AddCreative : DbMigration
{
    public override void Up()
    {
        AddColumn("Authors", "Names", c => c.String(maxLength: 4000));
        Sql("UPDATE [Authors] SET [Names] = [Name]");
        DropColumn("Authors", "Name");
    }

    public override void Down()
    {
        AddColumn("Authors", "Name", c => c.String(maxLength: 4000));
        Sql("UPDATE [Authors] SET [Name] = [Names]");
        DropColumn("Authors", "Names");
    }
}
于 2012-07-12T23:42:07.827 回答