在应用程序启动时通过代码触发EF迁移 [英] Triggering EF migration at application startup by code

查看:112
本文介绍了在应用程序启动时通过代码触发EF迁移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在开发过程中,使用Update-Database命令使用Entity Framework Migrations(Beta1)都很好.

Using Entity Framework Migrations (Beta1), using Update-Database command is all good during development.

但是,当应用程序在某位客户的服务器上运行时,我真的希望我的应用程序在启动时自动将其数据库架构更新为最新版本.

But when the application is running on some customer's server somewhere, I really want my application to automatically update it's database schema to the latest version when it's started.

这可能吗?文档稀缺.

推荐答案

在RTM之前,他们没有提供执行此操作的方法,此时,他们已承诺提供命令行应用程序和msdeploy提供程序. 来源: http://blogs. msdn.com/b/adonet/archive/2011/11/29/code-first-migrations-beta-1-released.aspx

They aren't providing a way to do this until RTM, at which point they have promised a command line app and a msdeploy provider. Source: http://blogs.msdn.com/b/adonet/archive/2011/11/29/code-first-migrations-beta-1-released.aspx

当然不满意,powershell命令存储在packages目录中并且是纯文本格式,它似乎只是加载了一个存储在同一目录中的名为EntityFramework.Migrations.Commands的程序集.

Of course not being satisfied with that, the powershell command is stored in the packages directory and is plain text, it appears to just load up an assembly called EntityFramework.Migrations.Commands stored in the same directory.

通过该程序集,我想到了以下内容

Tracing through that assembly I came up with the following

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);            
  }
}

更新:经过一番实验,我发现了更多的东西

UPDATE: after a bit of experimentation I figured out a few more things

  • 在静态构造函数中为您的上下文执行更新很不好,因为它会破坏powershell命令,而以另一种方式(将代码添加到应用程序启动中)(Global.asax,WebActivator或Main方法)则要好得多
  • 以上代码仅在使用AutomaticMigrations时有效,您需要将其设置为MigrationsNamespace以便在手动创建的迁移中使用
  • 我正在创建的配置类应该已经存在于您的项目中(安装迁移nuget软件包时已添加),因此只需实例化它即可.

这意味着代码被简化为

DbMigrator dbMigrator = new DbMigrator(new NAMESPACE.TO.MIGRATIONS.Configuration());
dbMigrator.Update(null);        

这篇关于在应用程序启动时通过代码触发EF迁移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆