Leverage FluentMigrator in ASP.NET Core 2.0

Let’s see how easy it is to¬†use FluentMigrator in ASP.NET Core 2.0 ūüôā

If this is the first time you hear about FluentMigrator then here is the description from https://fluentmigrator.github.io/

Fluent Migrator is a migration framework for .NET much like Ruby on Rails Migrations. Migrations are a structured way to alter your database schema and are an alternative to creating lots of sql scripts that have to be run manually by every developer involved.¬†Migrations solve the problem of evolving a database schema for multiple databases (for example, the developer’s local database, the test database and the production database). Database schema changes are described in classes written in C# that can be checked into a version control system.

Basically, you if you want to make it easier to maintain database schema and structures in case if any new changes happen it can be applied and tracked throughout the whole lifecycle of the project.

Lately by introducing ASP.NET Core, a lot of former ASP NET code will not work or was deprecated, actually, there is a better, cleaner way to handle the migration. Let’s go through each step:

  1. Import the following Nugets
    • FluentMigrator.Runner
    • FluentMigrator
  2. Create a simple ASP.NET Core application from the template and open Startup class, add the following to ConfigureServices:
services.AddFluentMigratorCore()
    .ConfigureRunner(
        builder => builder
               .AddSQLite()
               .WithGlobalConnectionString("")
               .ScanIn(typeof(object).Assembly).For.Migrations())

3. Depending you are using SQL, MySQL you can add the appropriate extension method, add the connection string and the assembly that has the migrations such as below:

[Migration(20090906205440)]
    public class AddNotesTable : Migration
    {
        public override void Up()
        {
            Create.Table("Notes")
                .WithIdColumn()
                .WithColumn("Body").AsString(4000).NotNullable()
                .WithTimeStamps()
                .WithColumn("User_id").AsInt32();
        }

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

The above just create a simple table with a bunch of columns.

Finally, you need to execute the migrations. To do that, you can easily resolve the dependency to IMigrationRunner and execute:

// Instantiate the runner
var runner = serviceProvider.GetRequiredService<IMigrationRunner>();

// Run the migrations
runner.MigrateUp();

You can get serviceProvider anywhere in your code by injecting IServiceProvider to your constructor.

I think that was pretty awesome and super easy to Use FluentMigrator in ASP.NET Core 2.0

You may also like...

Leave a Reply

Your email address will not be published.