Start migrations in FluentMigrator

2.1k views Asked by At

I need to use FluentMigrator in order to execute my database migrations. FluentMigrator seems to be a good and easy-to-use library. But I think I'm missing something... how to start a migration? How to set the database type? How to set the connection string?

In the GitHub I can't find a main() method or some entry point

Thanks a lot!

3

There are 3 answers

0
UnitStack On

I wrote a helper for this, check it out here

https://github.com/Diginari/FluentMigrator-MVC-Helper

0
Castrohenge On

To run your migrations you need to use one of the Migration runners - https://github.com/schambers/fluentmigrator/wiki/Migration-Runners.

These allow you to run your migrations directly from the command line or from within Nant, MSBuild or Rake. The documentation outlines how to set your connection string and specify the database type.

0
Stas Ivanov On

Most probably, you are looking for Migration runners. Here is the code for in-process migration runner from the documentation page:

using System;
using System.Linq;

using FluentMigrator.Runner;
using FluentMigrator.Runner.Initialization;

using Microsoft.Extensions.DependencyInjection;

namespace test
{
    class Program
    {
        static void Main(string[] args)
        {
            var serviceProvider = CreateServices();

            // Put the database update into a scope to ensure
            // that all resources will be disposed.
            using (var scope = serviceProvider.CreateScope())
            {
                UpdateDatabase(scope.ServiceProvider);
            }
        }

        /// <summary>
        /// Configure the dependency injection services
        /// </summary>
        private static IServiceProvider CreateServices()
        {
            return new ServiceCollection()
                // Add common FluentMigrator services
                .AddFluentMigratorCore()
                .ConfigureRunner(rb => rb
                    // Add SQLite support to FluentMigrator
                    .AddSQLite()
                    // Set the connection string
                    .WithGlobalConnectionString("Data Source=test.db")
                    // Define the assembly containing the migrations
                    .ScanIn(typeof(AddLogTable).Assembly).For.Migrations())
                // Enable logging to console in the FluentMigrator way
                .AddLogging(lb => lb.AddFluentMigratorConsole())
                // Build the service provider
                .BuildServiceProvider(false);
        }

        /// <summary>
        /// Update the database
        /// </summary>
        private static void UpdateDatabase(IServiceProvider serviceProvider)
        {
            // Instantiate the runner
            var runner = serviceProvider.GetRequiredService<IMigrationRunner>();

            // Execute the migrations
            runner.MigrateUp();
        }
    }
}