Search code examples
c#sql-serverdatabase-migrationfluent-migrator

How to run migration on only specific database name when using fluentMigrator


We are using .NET4.5, SQL2012 and FluentMigrator to control our database migrations. We are running multiple databases in our solution and we need to run some data inserts into some databases but not the others.

How can I run some database migrations based on specific database name?


Solution

  • I have introduced this class that controls which databases it should run on. So rather when inheriting from Migration you would now inherit from OnlyRunOnSpecificDatabaseMigration:

    One note!: It does fallback onto default behavior (to run migration) if there are no databases listed in DatabaseNamesToRunMigrationOnList - which some might find counter-intuitive

    namespace Infrastructure.Migrations
    {
        using System.Collections.Generic;
        using FluentMigrator;
        using FluentMigrator.Infrastructure;
    
        public abstract class OnlyRunOnSpecificDatabaseMigration : Migration
        {
            public abstract List<string> DatabaseNamesToRunMigrationOnList { get; }
    
            private bool DoRunMigraton(IMigrationContext context)
            {
                return this.DatabaseNamesToRunMigrationOnList == null ||
                       this.DatabaseNamesToRunMigrationOnList.Contains(new System.Data.SqlClient.SqlConnectionStringBuilder(context.Connection).InitialCatalog);
            }
    
            public override void GetUpExpressions(IMigrationContext context)
            {
                if (this.DoRunMigraton(context))
                {
                    base.GetUpExpressions(context);
                }
            }
    
            public override void GetDownExpressions(IMigrationContext context)
            {
                if (this.DoRunMigraton(context))
                {
                    base.GetDownExpressions(context);
                }
            }
        }
    }
    

    usage example:

    public class RiskItems : OnlyRunOnSpecificDatabaseMigration
    {
        public override void Up()
        {
    
            Execute.Sql(@"update [Items] set  
                        CanBeX = 
                        case when exists(select 1 from [SomeTable] where Key = [Items].Key and position like 'Factor%') then 1 else 0 end");
        }
    
        public override void Down()
        {
    
        }
    
        public override List<string> DatabaseNamesToRunMigrationOnList
        {
            get
            {
                return new List<string> {"my_database_name"};
            }
        }
    }