Using FluentMigrator

The FluentMigrator library allow us to create a database scheme, then modify it incrementaly it keeping track of previous versions.

Install the following packages (with a runner for MariaDB/MySQL):

  • FluentMigrator
  • FluentMigrator.Runner.MySql

Create a folder for migration definitions, then create classes with a version attribute like this:


[Migration(1)]
public class MigrationInitial : Migration
{
    public override void Up()
    {
        Create.Table("Users")
            .WithColumn("Id").AsInt32().PrimaryKey().Identity()
            .WithColumn("UserName").AsString().Nullable()
       
    }

    public override void Down()
    {
        Delete.Table("Users");
    }
}

Register the runner service:


builder.Services
        .AddFluentMigratorCore()
            .ConfigureRunner(rb => rb
                    .AddMySql8()
                    .WithGlobalConnectionString(builder.Configuration.GetConnectionString("connection"))
                    .ScanIn(
                        typeof(MyUser).Assembly,
                        typeof(AnotherClass).Assembly
                    ).For.Migrations()
                )
                .AddLogging(lb => lb.AddFluentMigratorConsole());

Inject the scoped service after building the ServiceProvider and use it to run all the upgrades



private static void UpdateDatabase(IServiceProvider serviceProvider)
{
    IMigrationRunner runner = serviceProvider.GetRequiredService<IMigrationRunner>();

    runner.MigrateUp();
}

using (var scope = app.Services.CreateScope())
{
    UpdateDatabase(scope.ServiceProvider);
    await SeedDatabase.Seed(scope.ServiceProvider);
}

More about the project can be found here: https://fluentmigrator.github.io/

Here are the main advangates over EntityFramework migration tools:

  • Execute custom SQL code while migrating
  • Working with an existing scheme, by checking if the tables already defined

Post a Comment

Previous Post Next Post