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

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

问题描述

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

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天全站免登陆