Is it possible to use fluent migrator in application_start?

前端 未结 2 902
南笙
南笙 2021-01-30 08:46

I\'m using fluent migrator to manage my database migrations, but what I\'d like to do is have the migrations run at app start. The closest I have managed is this:



        
2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-30 09:20

    PM> Install-Package FluentMigrator.Tools

    Manually add a reference to:

    packages\FluentMigrator.Tools.1.6.1\tools\AnyCPU\40\FluentMigrator.Runner.dll
    

    Note that the folder name will vary on version number, this illustration uses the current 1.6.1 release. If you need the .NET 3.5 runner use the \35\ directory.

    public static class Runner
    {
        public class MigrationOptions : IMigrationProcessorOptions
        {
            public bool PreviewOnly { get; set; }
            public string ProviderSwitches { get; set; }
            public int Timeout { get; set; }
        }
    
        public static void MigrateToLatest(string connectionString)
        {
            // var announcer = new NullAnnouncer();
            var announcer = new TextWriterAnnouncer(s => System.Diagnostics.Debug.WriteLine(s));
            var assembly = Assembly.GetExecutingAssembly();
    
            var migrationContext = new RunnerContext(announcer)
            {
                Namespace = "MyApp.Sql.Migrations"
            };
    
            var options = new MigrationOptions { PreviewOnly=false, Timeout=60 };
            var factory = 
                new FluentMigrator.Runner.Processors.SqlServer.SqlServer2008ProcessorFactory();
    
            using (var processor = factory.Create(connectionString, announcer, options))
            { 
                var runner = new MigrationRunner(assembly, migrationContext, processor);
                runner.MigrateUp(true);
            }
        }
    }
    

    Note the SqlServer2008ProcessorFactory this is configurable dependent upon your database, there is support for: 2000, 2005, 2008, 2012, and 2014.

提交回复
热议问题