【发布时间】:2011-12-14 16:47:27
【问题描述】:
使用 Entity Framework Migrations (Beta1),在开发过程中使用 Update-Database 命令都很好。
但是当应用程序在某个客户的服务器上运行时,我真的希望我的应用程序在启动时自动将其数据库架构更新到最新版本。
这可能吗?文档稀缺。
【问题讨论】:
标签: migration entity-framework-4.1 entity-framework-migrations
使用 Entity Framework Migrations (Beta1),在开发过程中使用 Update-Database 命令都很好。
但是当应用程序在某个客户的服务器上运行时,我真的希望我的应用程序在启动时自动将其数据库架构更新到最新版本。
这可能吗?文档稀缺。
【问题讨论】:
标签: migration entity-framework-4.1 entity-framework-migrations
直到 RTM 之前,他们才提供执行此操作的方法,此时他们已承诺提供命令行应用程序和 msdeploy 提供程序。 来源:http://blogs.msdn.com/b/adonet/archive/2011/11/29/code-first-migrations-beta-1-released.aspx
当然不满足于此,powershell 命令存储在 packages 目录中并且是纯文本,它似乎只是加载存储在同一目录中的名为 EntityFramework.Migrations.Commands 的程序集。
跟踪该程序集我想出了以下内容
public class MyContext : DbContext
{
static MyContext()
{
DbMigrationsConfiguration configuration = new DbMigrationsConfiguration() {
MigrationsAssembly = typeof(MyContext).Assembly,
ContextType = typeof(MyContext),
AutomaticMigrationsEnabled = true,
};
DbMigrator dbMigrator = new DbMigrator(configuration);
dbMigrator.Update(null);
}
}
更新:经过一些实验,我发现了更多的东西
这意味着代码被简化为
DbMigrator dbMigrator = new DbMigrator(new NAMESPACE.TO.MIGRATIONS.Configuration());
dbMigrator.Update(null);
【讨论】:
这个问题的另一个选项是添加
Database.SetInitializer<MyContext>(new MigrateDatabaseToLatestVersion<MyContext, NAMESPACE.TO.MIGRATIONS.Configuration>());
到您的Global.asax Application_Start 方法。
【讨论】: