FluentMigrator-在删除外键之前检查它是否存在

时间:2018-09-19 14:57:16

标签: c# .net sql-server fluent-migrator

我正在使用FluentMigrator将一个数据库模式迁移到另一个数据库模式。我有一种情况,我想在删除外键之前检查它是否存在。

以前,我只是通过执行以下操作删除外键:

Delete.ForeignKey("FK_TableName_FieldName").OnTable("TableName");

如何检查外键首先存在?

2 个答案:

答案 0 :(得分:1)

基于此https://stackoverflow.com/a/17501870/10460456,您可以使用Execute.WithConnection函数在删除外键之前测试其是否存在。

    Execute.WithConnection((connection, transaction) =>
    {
        DeleteForeignKeyIfExist(connection, transaction, "yourReferencedTable", "yourTable", "foreignColumnName", "foreignKeyName");
    });

    public bool DeleteForeignKeyIfExist(IDbConnection connection, IDbTransaction transaction, string referenceTable, string table, string foreignKeyColumn, string foreignKeyConstrainName)
    {
        using (var cmd = transaction.Connection.CreateCommand())
        {
            cmd.Transaction = transaction;
            cmd.CommandType = CommandType.Text;

            cmd.CommandText = ForeignKeyExistCommand(referenceTable, foreignKeyColumn);

            bool foreignKeyExist = false;
            using (var reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    // If this code is reached, the foreign key exist
                    foreignKeyExist = true;
                    break;
                }
            }

            if (foreignKeyExist)
            {
                cmd.CommandText = $"ALTER TABLE [{table}] DROP CONSTRAINT [{foreignKeyConstrainName}];";

                cmd.ExecuteNonQuery();
                return true;
            }
        }

        return false;
    }

    private string ForeignKeyExistCommand(string foreignTable, string innerColumn)
    {
        return $"SELECT OBJECT_NAME(f.parent_object_id) TableName, " +
                "COL_NAME(fc.parent_object_id, fc.parent_column_id) ColName " +
                "FROM sys.foreign_keys AS f INNER JOIN sys.foreign_key_columns AS fc " +
                "ON f.OBJECT_ID = fc.constraint_object_id INNER JOIN sys.tables t " +
               $"ON t.OBJECT_ID = fc.referenced_object_id WHERE OBJECT_NAME(f.referenced_object_id) = '{foreignTable}' " +
               $"and COL_NAME(fc.parent_object_id,fc.parent_column_id) = '{innerColumn}'";
    }

答案 1 :(得分:0)

这是使用FluentMigrator删除外键的方法:

if (!Schema.Table("TableName").Constraint("FK_TableName_FieldName").Exists())
{
   Delete.ForeignKey("FK_TableName_FieldName").OnTable("TableName");
}