Yes you can
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;
}
}
}
You are going to have two caveats (that I know of):
- If you call the function in the same migration more than once, the first one will
succeed, the others would fail, since the exists check requires the
schema context to be updated with the new tables, which
doesn't happen until the next migration (or until the current migration successfully executes).
- If you use AutoReversingMigrations, the expression won't be
automatically mapped to its coresponding down statments. Meaning
that the implicit down won't have any effect.
To use toe above extension and your example, you would do
public override void Up()
{
this.CreateTableIfNotExists("table", table => table.WithColumn("Id").AsInt32().NotNullable());
}