EF-代码优先-自动更新数据库 [英] EF - code first - automatic update database

查看:92
本文介绍了EF-代码优先-自动更新数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在代码中使用自动迁移,但是每次更改模型中的某些内容时,都需要手动运行 update-Database .我可以自动做到吗?

I want to use automatic migrations in my code, but every time I change something in the model I need to run update-Database manually. Can I do it automatically?

这是配置:

public class Configuration : DbMigrationsConfiguration<ManualContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
        AutomaticMigrationDataLossAllowed = true;
    }
    ...
}

AppActivator :

[assembly: WebActivator.PreApplicationStartMethod(typeof(AppActivator), "PreStart")]
[assembly: PostApplicationStartMethod(typeof(AppActivator), "PostStart")]
[assembly: ApplicationShutdownMethod(typeof(AppActivator), "Stop")]

namespace Manual.Web
{
  public static class AppActivator
  {
    public static void PreStart()
    {
      Database.SetInitializer(
               new MigrateDatabaseToLatestVersion<ManualContext,Configuration>());
      Database.SetInitializer(new ManualDbInitializer());

      MeasurementConfig.RegisterUnits();
      MiniProfilerPreStart();
    }
    ...
  }

和ManualDbInitializer-用于种子(第一次创建数据库时):

And ManualDbInitializer - for seed (when creating DB at first time):

public class ManualDbInitializer : CreateDatabaseIfNotExists<ManualContext>
{
    protected override void Seed(ManualContext context)
    {
        ManualDbInitializerSeed.SeedForDB(context);
    }
}

推荐答案

如果要部署应用程序,则可能希望它在应用程序启动时自动升级数据库(通过应用任何挂起的迁移).您可以通过注册MigrateDatabaseToLatestVersion数据库初始化程序来实现.数据库初始化程序仅包含一些用于确保正确设置数据库的逻辑.第一次在应用程序流程(AppDomain)中使用上下文时,将运行此逻辑.

If you are deploying your application you may want it to automatically upgrade the database (by applying any pending migrations) when the application launches. You can do this by registering the MigrateDatabaseToLatestVersion database initializer. A database initializer simply contains some logic that is used to make sure the database is setup correctly. This logic is run the first time the context is used within the application process (AppDomain).

http://msdn.microsoft.com/en-us/data/jj591621#initializer

这篇关于EF-代码优先-自动更新数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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