繁体   English   中英

使用fluentMigrator时如何仅对特定数据库名称运行迁移

[英]How to run migration on only specific database name when using fluentMigrator

我们正在使用.NET4.5SQL2012FluentMigrator 来控制数据库迁移 我们在解决方案中运行多个数据库,我们需要在某些数据库中运行一些数据插入,而在其他数据库中则不需要。

如何根据特定的数据库名称运行某些数据库迁移?

我已经介绍了控制该数据库在哪个数据库上运行的此类。 因此,当从Migration继承时,您现在将从OnlyRunOnSpecificDatabaseMigration继承:

注意!:如果DatabaseNamesToRunMigrationOnList中没有列出DatabaseNamesToRunMigrationOnList ,则它会回退到默认行为(运行迁移)-有些DatabaseNamesToRunMigrationOnList可能会违反直觉

namespace Infrastructure.Migrations
{
    using System.Collections.Generic;
    using FluentMigrator;
    using FluentMigrator.Infrastructure;

    public abstract class OnlyRunOnSpecificDatabaseMigration : Migration
    {
        public abstract List<string> DatabaseNamesToRunMigrationOnList { get; }

        private bool DoRunMigraton(IMigrationContext context)
        {
            return this.DatabaseNamesToRunMigrationOnList == null ||
                   this.DatabaseNamesToRunMigrationOnList.Contains(new System.Data.SqlClient.SqlConnectionStringBuilder(context.Connection).InitialCatalog);
        }

        public override void GetUpExpressions(IMigrationContext context)
        {
            if (this.DoRunMigraton(context))
            {
                base.GetUpExpressions(context);
            }
        }

        public override void GetDownExpressions(IMigrationContext context)
        {
            if (this.DoRunMigraton(context))
            {
                base.GetDownExpressions(context);
            }
        }
    }
}

用法示例:

public class RiskItems : OnlyRunOnSpecificDatabaseMigration
{
    public override void Up()
    {

        Execute.Sql(@"update [Items] set  
                    CanBeX = 
                    case when exists(select 1 from [SomeTable] where Key = [Items].Key and position like 'Factor%') then 1 else 0 end");
    }

    public override void Down()
    {

    }

    public override List<string> DatabaseNamesToRunMigrationOnList
    {
        get
        {
            return new List<string> {"my_database_name"};
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM