问题
I am doing data-migration for my project. But I have one question, for example: I have Book table with following fields:
ID Name Color
1 Java red
2 MVC blue
3 .Net blue
I tried to change the name of field from "Color" to "BookColor" using Code First tech. But after migration the table looked like this:
ID Name BookColor
1 Java null
2 MVC null
3 .Net null
I lost my field values. How can I make sure that all value are transfered?
I'm using Entity Framework with MVC3
EDIT This is my DBMigration Class:
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");
}
}
I have changed Name
to Names
after changing (I lost my data in name field).
回答1:
I had no problems using the following:
First, setup the migrations:
PM> Enable-Migrations
PM> Add-Migration RenameBookColorColumn
Then we setup the migrations class to perform the rename:
public class RenameBookColorColumn : DbMigration
{
public override void Up()
{
this.RenameColumn("Books", "Color", "BookColor");
}
public override void Down()
{
this.RenameColumn("Books", "BookColor", "Color");
}
}
Next, make a call to Update-Database
so we can perform the changes:
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]
And voila, it's renamed and the data is retained.
回答2:
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");
}
}
来源:https://stackoverflow.com/questions/11344309/data-migration-in-mvc3-using-ef-4-3