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