在 FluentMigrator 上创建 Table 之前检查 Table 是否存在

Check Table Exist Before Create Table On FluentMigrator

我正在寻找一种在创建 table 之前为流畅的迁移器检查编写扩展方法的方法,类似这样

Schema.TableIfNotExist("table").InSchema("dbo").WithColumn("Id").AsInt32().NotNullable()

是否可以写一个扩展方法?

是的,你可以

public static class Ex
{
    public static IFluentSyntax CreateTableIfNotExists(this MigrationBase self, string tableName, Func<ICreateTableWithColumnOrSchemaOrDescriptionSyntax, IFluentSyntax> constructTableFunction, string schemaName = "dbo")
    {
        if (!self.Schema.Schema(schemaName).Table(tableName).Exists())
        {
            return constructTableFunction(self.Create.Table(tableName));
        }
        else
        {
            return null;
        }       
    }
}

你将有两个警告(据我所知):

  1. 如果您多次调用同一个迁移中的函数,第一个将 成功,其他人会失败,因为存在检查需要 要使用新表更新的模式上下文, 直到下一次迁移(或直到当前迁移成功执行)才会发生。
  2. 如果使用AutoReversingMigrations,表达式就不会 自动映射到其对应的向下语句。意义 隐式向下不会有任何影响。

要使用 toe above extension 和你的例子,你会做

public override void Up()
{
    this.CreateTableIfNotExists("table", table => table.WithColumn("Id").AsInt32().NotNullable());
}