EF migrations: creating DbContext instance

ef-migrations entity-framework entity-framework-6

Question

Is it possible to "tell" migration how to create MyDbContext instance? By default it uses a public parameterless constructor and searches for the connection string in AppConfig with the same as MyDbContext class. Can I tell somehow configure migration to use some factory method to create MyDbContext instance, which it will use to to the migration?

1
2
10/19/2015 6:52:45 PM

Accepted Answer

You can create a class that implements the IDbContextFactory<MyDbContext> interface and that contains your custom code for creating an instance of MyDbContext.

Design-time tools as well as migrations tools will auto-discover this class (if it is palced in the same assembly as your DbContext) and will use it to initialize the MyDbContext.

public class MigrationsContextFactory : IDbContextFactory<MyDbContext> {
    public MyDbContext Create() {
        return new MyDbContext(connectionString, someOtherSettings);
    }
}

See documentation for reference.

2
10/19/2015 8:03:20 PM

Popular Answer

I don't know how to make migration uses a parameterless constructor of the DbContext, but I would use my configuration class and my Initializer to inject some connection string for example. Maybe it can help you.

public class MyDbInitializer : IDatabaseInitializer<MyDbContext>
{
    private readonly DbMigrationsConfiguration _configuration;

    public MyDbInitializer(string connection)
    {
        _configuration = new Configuration(connection);
    }

    public void InitializeDatabase(MyDbContext context)
    {
        if (!context.Database.Exists())
        {
            context.Database.Create();
        }
        else
        {
            var migrator = new DbMigrator(_configuration);
            if (migrator.GetPendingMigrations().Any())
                migrator.Update();
        }
    }
}

internal sealed class Configuration : DbMigrationsConfiguration<MyDbContext>
{
    public Configuration(string connectionString)
    {
        this.TargetDatabase = new System.Data.Entity.Infrastructure.DbConnectionInfo(connectionString);
        AutomaticMigrationsEnabled = true;
        ContextKey = "MyProj.Models.MyDbContext";
    }
}

public MyDbContext()
{

}

public MyDbContext(string connection)
{
   Database.SetInitializer(new MyDbInitializer(connection));
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow