Search code examples
c#.netmigrationfluent-migrator

Check Table Exist Before Create Table On FluentMigrator


I'm looking for a way to write a extension method for fluent migrator check before create table, something like this

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

is it possible to write a extension method ?


Solution

  • 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):

    1. 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).
    2. 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());
    }