【问题标题】:FluentMigrator - Check if column exists cross databaseFluentMigrator - 检查列是否存在跨数据库
【发布时间】:2021-12-11 03:24:48
【问题描述】:

我正在使用 FluentMigrator 将多个数据库迁移到不同的架构。

如何检查某个列是否存在于另一个数据库的表中?

public override void Up()
{
    //this line by default uses the current DB context and it works fine
    var columnExistsInThisDb = Schema.Table("Subjects").Column("MatterKey").Exists();

    //here I would like to check if column exist in "AnotherDatabase", 
    //but I didn't manage to make it work
    var columnExistsInAnotherDb = 

            Database("AnotherDatabase") //<--- this is pseudo-code of what I would like to achieve 
                .Schema.Table("Subjects").Column("MatterKey").Exists();


    if (columnExistsInThisDb || columnExistsInAnotherDb)
    {
        Execute.Sql("--DO STUFF");
    }
}

我尝试了以下方法,但即使列存在,它也会返回 FALSE。

var columnExistsInAnotherDb = Schema.Table("AnotherDatabase.dbo.Subjects").Column("MatterKey").Exists()

【问题讨论】:

    标签: c# sql fluent-migrator


    【解决方案1】:

    总的来说这是个坏主意。流利的迁移器应该自己处理模式。在其他情况下 - 没有理由使用它。我会推荐你​​使用fluent migrator tags。它们是为处理不同的数据库而创建的。

    但是,如果您真的想按照您的描述进行操作 - 这是如何调用数据库脚本的示例(您将从父类获得的所有内容):

    Execute.WithConnection((IDbConnection connection, IDbTransaction transaction) =>
                {
                    var command = connection.CreateCommand();
                    command.Transaction = transaction;
                    command.CommandText = "SELECT * " +
                           "FROM INFORMATION_SCHEMA.COLUMNS " +
                           "WHERE table_name = 'tableName' " +
                           "AND table_schema = 'schema'" + 
                           "AND column_name = 'columnName'";
                    var count = command.ExecuteScalar();
                });
    

    【讨论】:

    • 你是对的,但在我的情况下,我有一个边缘情况,我需要检查该列是否存在于两个数据库中。不过,您的回答是很好的启发。谢谢。
    • 所以我的第二个选项应该适合你)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    • 2014-07-08
    • 2019-06-24
    • 2014-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多