简体   繁体   中英

Entity Framework 6 - How to update customer's database with CodeFirst migration

My team develops an application which deploys MSSQL database at customer's system. We encountered a problem with using migrations to update the customer's database structure .

We can't use automated migrations because more than one instance of the app can run on the same database so if one of instances gets updated and therefore changes the model and therefore the structure of database the others change it back so neither of them can work on the database.

We can't use nonautomated migrations because we have no access to customer's database to run the update-database command.

The question is what's the best approach to keep the database and the model always up to date on the level of code ?

You have to use the migrate to latest version strategy. This apporach allows you to automatically update the database when the model is changed:

Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyDbContext, MyMagicDatabaseConfiguration>()`);
 public class MyMagicDatabaseConfiguration : DbMigrationsConfiguration<MyDbContext>
  {
    public MyMagicDatabaseConfiguration()
    {
      this.AutomaticMigrationsEnabled = true;
      this.AutomaticMigrationDataLossAllowed = true;
    }
  }

// !!Force the initialization. this will execute the update!!
MyDb.Context.Database.Initialize(true); 

This works fine if you are using MS SQL Server


The problem you are using MySql you have to do everything by your self!:

   var migrator = new DbMigrator(new DbMigrationsConfiguration  ());

   migrator.Update();

   // In the migrtaions directory:

   public partial class MyMigration : DbMigration
   {
     public override void Up()
     {
        AddColumn("dbo.MyTable", "AnyName", c => c.Boolean(nullable: false));
     }
     public override void Down()
     {
       DropColumn("dbo.MyTable", "AnyName");
     }
   }

This is not an easy work and I do not recommeded you to do it. Just use SQL Server apporach this will safe your time. one note more: Magic migration sometimes does not working(Complex changes with keys), if the changes can not be handled automatically.

You can also use migration to a target version:

 var configuration = new DbMigrationsConfiguration();
      var migrator = new DbMigrator(configuration);

      migrator.Update("HereMigrationId");
      var scriptor = new MigratorScriptingDecorator(migrator);
      var migrationScript = scriptor.ScriptUpdate(sourceMigration: null, targetMigration: "HereMigrationId");

In your case you need migration to target version. with the decrator you can modifiy the migration script during the migration.

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