Add multiple databases to FluentMigrator in ASP.NET Core

In one of my past blog post I talked about how to use FluentMigrator in ASP.Net Core 2.0, in this one, I am going through use multiple databases for FluentMigrator in ASP.NET Core.

Although setting up FluentMigratror is pretty straightforward, for some reason setting it up to work with multiple databases, is not documented well enough. I try to make it simple here.

So once you got your basic FluentMigrator setup in your ASP.Net Core app, which I explained in my previous blog post, then you need to do a few adjustments using a couple of easy extension method to handle multiple databases such as SQL, MySQL, etc.

You should have something like below code for SQL:

services.AddFluentMigratorCore()
    .ConfigureRunner(
        builder => builder
               .AddSQLite()
               .WithGlobalConnectionString("")
               .ScanIn(typeof(object).Assembly).For.Migrations())

Now if you want to have MySQL or any other sort of database added to this you just need to use the appropriate extension method, in this case, AddMySQL().

Then since have mutliple connection string you can’t use WithGlobalConnectionString() extension method anymore you have to configure ProcessorOptions and SelectingGeneratorAccessorOptions.

  • ProcessorOptions provides options for setting connection string and command timeout.
  • SelectingGeneratorAccessorOptions provides the options for setting processor id or basically type of database (MySQL/SQL)

Here is the complete code:

var serviceProvider = new ServiceCollection().AddFluentMigratorCore()
               .AddLogging(lb => lb.AddFluentMigratorConsole())
               .Configure<FluentMigratorLoggerOptions>(cfg => {
                   cfg.ShowElapsedTime = true;
               })
               .ConfigureRunner(
                   builder => builder
                          .AddSqlServer()
                          .AddMySql5()
                          .ScanIn(typeof(AddNewTable).Assembly).For.Migrations())
                .Configure<ProcessorOptions>(x => x.ConnectionString = provider == "sql" ? "YOUR SQL CONNECTION STRING" : "YOUR MYSQL CONNECTION STRING")
                .Configure<SelectingGeneratorAccessorOptions>(cfg =>  cfg.GeneratorId = provider == "sql" ? "sqlserver" : "addmysql")
                .BuildServiceProvider();

and here is the migrator class which holds actual DB creation:

use multiple databases for FluentMigrator in ASP.NET Core

I guess that’s it for this post and how to use multiple databases for FluentMigrator in ASP.NET Core.

You may also like...

Leave a Reply

Your email address will not be published.