Search code examples
c#fluent-migrator

Changing conventions with FluentMigrator


Where is the appropriate place to override the default migration conventions in FluentMigrator? Should it be done with the runner, or inside a migration? Or elsewhere?

Specifically, I would like to change the index naming convention to match that used by ServiceStack (e.g. IX_Foo_Bar => uidx_foo_bar).

I see the method MigrationBase.ApplyConventions(IMigrationContext ) where IMigrationContext has an IMigrationConventions property... Should I create my own MigrationContext inside the migration? What if I want all migrations to use the same conventions?


Solution

  • This is the only way I found to change the conventions. You need to create an abstract class that extends "FluentMigrator.Migration" changing its conventions. Then, all your migration class should extend this class instead of FluentMigrator.Migration.

    public abstract class BaseMigration : Migration
    {
        // Update conventions for up migration
        public override void GetUpExpressions(IMigrationContext context)
        {
            this.UpdateConventions(context);
            base.GetUpExpressions(context);
        }
    
        // Update conventions for down migration
        public override void GetDownExpressions(IMigrationContext context)
        {
            this.UpdateConventions(context);
            base.GetDownExpressions(context);
        }
    
        // Change the conventions
        public void UpdateConventions(IMigrationContext context)
        {
            var conventions = ((MigrationConventions)context.Conventions);
            conventions.GetIndexName = index => DefaultMigrationConventions.GetIndexName(index).Replace("IX_", "uidx_");
        }
    }