mcs_dodo
mcs_dodo

Reputation: 738

Entity Framework IDatabaseInitializer to recreate tables of a DbContext

The Entity Framework provides very few implementations of IDatabaseInitializers. I managed to implement a DropAndMigrateToNewest like this:

public class DropAndMigrateToNewest<TContext, TMigrationsConfiguration> : IDatabaseInitializer<TContext> 
    where TContext : DbContext
    where TMigrationsConfiguration : DbMigrationsConfiguration<TContext>, new()
{
    private readonly DbMigrationsConfiguration<TContext> _configuration;

    public DropAndMigrateToNewest()
    {
        _configuration = new TMigrationsConfiguration();
    }

    public void InitializeDatabase(TContext context)
    {
        context.Database.Delete();

        var migrator = new DbMigrator(_configuration);
        migrator.Update();
    }
}

What I need now is an initializer that will not delete existing database (since we have multiple schemas built with migrations in it) but do something that is achieved in console with

Update-Database -TargetMigration $InitialDatabase

and then just Update-Database.

The DbMigrator.Update method takes as an argument the migration name, but it won't work with "$InitialDatabase". I dug into https://github.com/mono/entityframework/blob/master/src/EntityFramework/Migrations/DbMigrator.cs but was of no help ...

Upvotes: 3

Views: 564

Answers (1)

mcs_dodo
mcs_dodo

Reputation: 738

Found a solution: migrator.Update("0"); and then migrator.Update(); does the job.

public class RecreateFromScratch<TContext, TMigrationsConfiguration> : IDatabaseInitializer<TContext>
    where TContext : DbContext
    where TMigrationsConfiguration : DbMigrationsConfiguration<TContext>, new()
{
    private readonly DbMigrationsConfiguration<TContext> _configuration;

    public RecreateFromScratch()
    {
        _configuration = new TMigrationsConfiguration();
    }

    public void InitializeDatabase(TContext context)
    {
        var migrator = new DbMigrator(_configuration);
        migrator.Update("0");
        migrator.Update();
    }
}

Upvotes: 2

Related Questions