【问题标题】:How to run migration on only specific database name when using fluentMigrator使用 fluentMigrator 时如何仅在特定数据库名称上运行迁移
【发布时间】:2016-11-24 23:32:00
【问题描述】:

我们正在使用.NET4.5SQL2012FluentMigrator to control our database migrations。我们在我们的解决方案中运行多个数据库,我们需要在一些数据库中运行一些数据插入,而不是在其他数据库中。

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

【问题讨论】:

  • 这个 Q/A 为我节省了很多时间,我希望它得到更多的支持。可能会添加一些上下文,例如“FM 运行它可以在给定 dll 中找到的所有迁移”、“标签属性对特定迁移很有用,但它们的目的肯定不会普及”和“文档告诉您如何针对不同的 DBMS,但是没有关于不同数据库的任何内容”,因此很明显文档是贫乏的,而不是您在询问之前没有进行适当的搜索。
  • @RenaudGauthier 嗨 Renaud,这个 Q 没有得到支持的原因不是措辞(标题对应于答案中的内容)但问题非常小众,只看观点......我也不'不够关心 TBH...在 SO 上帮助人们并不是很有意义,所以我'退休'..

标签: c# sql-server database-migration fluent-migrator


【解决方案1】:

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

注意!:如果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"};
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-01
    • 2019-11-15
    • 1970-01-01
    • 1970-01-01
    • 2021-07-03
    • 1970-01-01
    • 2018-03-04
    相关资源
    最近更新 更多