实体框架迁移者的连接 [英] Entity Framework migrator's connection
问题描述
使用实体框架5.0,我试图在我的MVC网站的启动例程期间手动迁移我的代码优先数据库。为此,我首先创建一个DbContext实例,然后运行以下代码:
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);
我假定与dataContext的连接关联的数据库将被迁移。看来,情况并非如此。相反,它总是尝试在本地的SQLExpress实例上迁移一个数据库。
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.
MigrateDatabaseToLatestVersion构造函数有一个重载,它使用一个DB连接字符串名称,但是我的项目是使用Azure并且不使用标准的ConnectionStrings配置部分。理想情况下,我只是传递一个可用的连接字符串。这是可能的吗?
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?
推荐答案
解决方案是完全绕过MigrateDatabaseToLatestVersion类。它只是DbMigration类的一个薄薄的包装,如在源代码中显示。
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();
这篇关于实体框架迁移者的连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!