Question

We are running Entity Framework 5 with Code First and Migrations Enabled. Running with the database initializer: MigrateToLatestVersion

We have several customers live that run on the latest stable branch. While we develop new code in our trunk/master, we sometimes have the need to connect to the customers database running on branched code, fx. to debug some sort of data bug.

This can be "dangerous" if someone forgot to switch to the branch the customer is running, because migrations will then upgrade the customers database to fit whatever code that person is running.

One solution would be to run another initializer that doesnt migrate to the latest version. But that would mean a lot more work when we deploy new systems to new customers or someone new joins the team and needs go get up and running.

We were thinking of solving this problem by having a bool in the app.config to set if the code should "Migrate To Latest Version" and then always have that to false for development, and then transforming it when deploying to customers.

That way we get the benefit of still having the database updating to the newest version automaticly, but not the danger of a developer accidentally connecting to a system of an older version of the code, and migrations destroying that database.

So now that we have that, we basicly need to check this:

(simplified code)

if(Config.MigrateToLatestVersion || !databaseExists) 
{
  var initializer = new MigrateToLatestVersion<MyContext,MigrationConfiguration>();
  Database.SetInitializer(initializer);
  using(var context = new MyContext())
  {
    context.Database.Initialize(true)
  }
}

My question was going to be about how to check if the database exists without running migrations, but i found out you can do this:

Database.SetInitializer<MyContext>(null);
var context = new MyContext();
var databaseExists = context.Database.Exists();

But if i only run the MigrateToLatestVersion initializer when the database doesnt exist or when i manually run Update-Database from the package-manager console.

I have 2 problems, first: I no longer get an exception saying if my model is different from the database, which i would still like. second: it doesnt run the seed method located in my MigrationConfiguration, which i might still want to run.

Any suggestions on how i can still run the Migrations Initializer to get all the benefits, but still have something that prevents someone from potentially breaking our production environments by accident?

Was it helpful?

Solution

So the solution i went with was to make a new DatabaseInitializer called MigrateDatabaseToLatestIfLocal

Looking how the MigrateDatabaseToLatestVersion initializer worked, i did something very similar, with the difference of checking if the database exists and if we were running locally or remote (With the help of config transformations to determine this. The remote system has it's datasource transformed in the config file.)

public class MigrateDatabaseToLatestIfLocal<TContext, TMigrationsConfiguration> : IDatabaseInitializer<TContext>
        where TContext : DbContext
        where TMigrationsConfiguration : DbMigrationsConfiguration<TContext>, new()
    {
        private DbMigrationsConfiguration _config;

        public MigrateDatabaseToLatestIfLocal()
        {
            this._config = (DbMigrationsConfiguration)Activator.CreateInstance<TMigrationsConfiguration>();
        }

        public MigrateDatabaseToLatestIfLocal(string connectionStringName)
        {
          MigrateDatabaseToLatestIfLocal<TContext, TMigrationsConfiguration> databaseToLatestVersion = this;
          var instance = Activator.CreateInstance<TMigrationsConfiguration>();
          instance.TargetDatabase = new DbConnectionInfo(connectionStringName);
            databaseToLatestVersion._config = instance;
        }

        public void InitializeDatabase(TContext context)
        {
            var databaseExists = context.Database.Exists();

            var migrator = new DbMigrator(this._config);
            var pendingMigrations = migrator.GetPendingMigrations().OrderByDescending(s => s);
            var localMigrations = migrator.GetLocalMigrations().OrderByDescending(s => s);
            var dbMigrations = migrator.GetDatabaseMigrations().OrderByDescending(s => s);


            var isRemoteConnection = FunctionToFindOutIfWeAreRemote(); //here we check the config file to see if the datasource is a certain IP, this differentiates locally and remotely because of config tranformation.

            if (isRemoteConnection && databaseExists)
            {
                if (pendingMigrations.Any())
                {
                    throw new MigrationsException("You are not allowed to automatically update the database remotely.")
                }
                if (localMigrations.First() != dbMigrations.First())
                {
                    throw new MigrationsException("Migrations in code and database dont match, please make sure you are running the code supported by the remote system. ");
                }
            }
            else
            {
                //we are local, fine update the db and run seeding.
                //we are remote and the db does not exist, fine update and run seed.
                migrator.Update();
            }
        }
    }

This might be a very special case, but to me it provides some safety when running code first migrations, that make sure you dont just randomly migrate a live environment accidently

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top