简体   繁体   中英

EF Code First Migration - Property migration

So Imagine this situation:

namespace SC.BL.Domain
{
  public class User
  {
    public String Name { get; set; }
    public String Adress { get; set; }
    public int PhoneNumber { get; set; }
    public char Gender { get; set; }
  }
}

EF Code first migration is enabled. I implemented code-based migration by using 'enable-migrations'

My DbInitializer is set to use the MigrateDatabaseToLatestVersion initializer

Now my question is, I would like to migrate one property into multiple properties, without the loss of data, after this the old property may be removed!

Suppose I have in my database the following,

Name: User1

Address: Emmalaan 2, Gelderland

PhoneNumber: 0471250950

Gender: M

Now I want to change my User class to the following:

namespace SC.BL.Domain
    {
      public class User
      {
        public String Name { get; set; }
        public String StreetName { get; set; }
        public int HouseNumber { get; set; }
        public String City { get; set; }
        public int PhoneNumber { get; set; }
        public char Gender { get; set; }
      }
    }

So now I want that after migrations, the data in the database is changed (without dataloss) and put in the right properties. Where can I till the migrator to do something like this?

Name: User1

StreetName: Emmalaan 2

HouseNumber: 2

City: Gelderland

PhoneNumber: 0471250950

Gender: M

Is this possible via migration? And how is this done?

I think that the only thing you could do is the editing of the generated migration to do the transformation you want.

Inside Up() method of the migration:

  1. use the Sql() method to write the data into a temporary table
  2. migrate the table to the new structure (with the generated code)
  3. use the Sql() method to take all the data (splitted as you want) from the temporary table so you can fill the edited table

in the Down() method the inverse of Up() .

I don't think that this is possible via migration. You want to change structure of table, and you want that migration automatically separate data in different columns. I think that this is not possible. I think that better way is to only add columns by migration and after that you can create SQL procedure for splitting and updating data to different columns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM