我们正在使用.NET4.5
,SQL2012
和FluentMigrator
to control our database migrations。我们在我们的解决方案中运行多个数据库,我们需要在某些数据库中运行一些数据插入,而不是其他数据库。
如何根据特定的数据库名称运行某些数据库迁移?
答案 0 :(得分: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"};
}
}
}