EF migrations: creating DbContext instance

ef-migrations entity-framework entity-framework-6

Question

Is it possible to instruct migration on how to construct an instance of MyDbContext? By default, it looks for the connection string in AppConfig using the same search criteria as the MyDbContext class and uses a public constructor without parameters. Can I tell migration to use a factory method to generate an instance of MyDbContext, which it will use to do the migration, in some way?

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

Accepted Answer

You may develop a class that uses theIDbContextFactory<MyDbContext> interface, which includes the code you wrote to create an instance ofMyDbContext .

If this class is located in the same assembly as your migration tool, both design-time tools and migration tools will automatically discover it.DbContext ) and will utilize it to launch theMyDbContext .

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

documentation is a good place to start.

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

Popular Answer

I'm not sure how to make migration use the DbContext's parameterless constructor, but I would use my configuration class and Initializer to inject, for instance, a connection string. You could benefit from it.

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