-
-
Save ManfredLange/023f5a4eab3f5dc5a7659e1a7d5fd2f5 to your computer and use it in GitHub Desktop.
Database class with code to run migration using Fluent Migrator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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