Entity Framework 5 Data Migrations

I have an entity with a string property that I need to ecrize into another set of objects:

public class MyEntity { public int Id { get; set; } public string FavoriteColor { get; set; } } 

I would like to change this to:

 public class MyEntity { public int Id { get; set; } public Color FavoriteColor { get; set; } public int FavoriteColorId { get; set; } } public class Color { public int Id { get; set; } public string Name { get; set; } } 

If I create a hyphen, it creates a new Color table in db, and then adds new columns to MyEntity. How can I guarantee that I will not lose all the data that exists as a string on "MyEntity"? I tried loading the DbContext into the transfer to create new β€œcolor” entities based on the string data in β€œMyEntity”, but it has problems because it detects that the model is out of sync with the current schema.

+4
source share
2 answers

In your project, go to the package manager windows and:

  • Enable Migration: Enable-Migrations
  • Create Migration: Add-Migration Initial
  • Create update / downgrade script: Update-Database

In this case, you add a new table ( Color ) and two new columns.

You have a reason, if you run your site, FavoriteColor will be deleted, including its data.

What can you do:

In the package manager console, when you run the Add-Migration Initial , which will create a new script (C # file). As you can see in this file, one column is deleted, 2 and 1 tables are added.

Make sure the table is created before the columns, fills it with data, creates 2 columns with existing data based on the old column, and then deletes the column.

Another way (perhaps better) to do this in several migration scenarios, you can also use the Seed() method to populate the data.

+3
source

If you create a migration using Add-Migration , the migration file will look like this:

 Up() { CreateTable("dbo.Color"...); DropColumn("FavoriteColor"); AddColumn("FavoriteColor", c=>Int(nullable: false)); // Some other code } 

You can modify this file to implement data transfer .

 Up() { CreateTable("dbo.Color"...); AddColumn("FavoriteColor", c=>Int(nullable: false)); Sql("INSERT INTO dbo.Color (Id, Name) SELECT DISTINCT FavoriteColor FROM dbo.MyEntity"); // And the other data corrections here using Sql() method. DropColumn("FavoriteColor"); // Some other code } 
+1
source

Source: https://habr.com/ru/post/1501060/


All Articles