如何在使用fluentMigrator时仅对特定的数据库名称运行迁移
本文关键字:数据库 迁移 运行 fluentMigrator | 更新日期: 2023-09-27 17:58:06
我们使用.NET4.5
、SQL2012
和FluentMigrator
来控制数据库迁移。我们在解决方案中运行多个数据库,我们需要在一些数据库中运行一些数据插入,但不需要在其他数据库中运行。
如何根据特定的数据库名称运行一些数据库迁移
我引入了这个类,它控制应该在哪些数据库上运行。因此,当从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"};
}
}
}