Question

Until now, I have been using automatic migrations to update my database from my model. I have now updated the dbContext() constructor from using a web.config database connection string, to dynamically setting the connection string context based on the user/company. This is built by looking up the details from another database.

This all works well until I make changes to my model. I can no longer run update-database from the Package Manager Console to update my database as there is no reference to a database instance in the code.

How do I now make the changes to my databases?

public MyContext() : base(ConnectionString())
{
}

private static string ConnectionString()
{
    SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
    sqlBuilder.DataSource = CurrentCompany.DataSource;
    sqlBuilder.InitialCatalog = CurrentCompany.InitialCatalog; 
    sqlBuilder.PersistSecurityInfo = true;
    sqlBuilder.IntegratedSecurity = true;
    sqlBuilder.MultipleActiveResultSets = true;
    return sqlBuilder.ToString();
}
Was it helpful?

Solution

You can add following line before the first database call:

Database.SetInitializer<MyContext>(new MigrateDatabaseToLatestVersion<MyContext, MyContextConfiguration>());

It will execute all pending (or automatic) migrations on MyContext creation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top