Skip to content

Instantly share code, notes, and snippets.

@ManfredLange
Created November 10, 2020 20:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ManfredLange/023f5a4eab3f5dc5a7659e1a7d5fd2f5 to your computer and use it in GitHub Desktop.
Save ManfredLange/023f5a4eab3f5dc5a7659e1a7d5fd2f5 to your computer and use it in GitHub Desktop.
Database class with code to run migration using Fluent Migrator
using System;
using FluentMigrator.Runner;
using Microsoft.Extensions.DependencyInjection;
namespace CmdLine.DataAccess
{
public class Database
{
public static void RunMigrations()
{
var serviceProvider = CreateServices();
// Put the database update into a scope to ensure
// that all resources will be disposed.
using (var scope = serviceProvider.CreateScope())
{
RunMigrations(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 SqlServer support to FluentMigrator
.AddSqlServer()
// Set the connection string
.WithGlobalConnectionString(ConnectionString)
// Define the assembly containing the migrations
.ScanIn(typeof(Database).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 RunMigrations(IServiceProvider serviceProvider)
{
// Instantiate the runner
var runner = serviceProvider.GetRequiredService<IMigrationRunner>();
// Execute the migrations
runner.MigrateUp();
}
private const string ConnectionString = "Server=database,1433;Database=mahi-cmdline;User ID=sa;Password=PassWord42";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment