Entity Framework migrator's connection

2019-05-27 05:54发布

问题:

Using the Entity Framework 5.0, I am attempting to manually migrate my code-first database during my MVC site's start up routine. To do this, I first create a DbContext instance and then run the following code:

var migrator = new MigrateDatabaseToLatestVersion<DataContext, Configuration>();
migrator.InitializeDatabase(this.dataContext);

I assumed the database associated with the dataContext's connection would be the one migrated. It appears though that this is not the case. Instead, it always tries to migrate a database on a local SQLExpress instance.

There is an overload to the MigrateDatabaseToLatestVersion constructor that takes a DB connection string name, but my project is using Azure and doesn't use the standard ConnectionStrings configuration section. Ideally, I'd just pass it a connection string, which I have available. Is this possible?

回答1:

The solution is to bypass the MigrateDatabaseToLatestVersion class entirely. It's just a thin wrapper around the DbMigration class, as shown in the source code.

In the end, I wrote the following code:

var database = this.dataContext.Database;
var migrationConfiguration = new Configuration();
migrationConfiguration.TargetDatabase = new DbConnectionInfo(database.Connection.ConnectionString, "System.Data.SqlClient");
var migrator = new DbMigrator(migrationConfiguration);
migrator.Update();