在应用自动迁移之前询问

时间:2015-07-06 03:46:00

标签: ef-migrations

如果我的数据库版本已过期,我希望我的演示win-forms应用程序询问用户是否应用自动迁移。

我从MSDN看到自动迁移由

控制
AutomaticMigrationsEnabled = true  // or false

在迁移配置类中。

所以我可以在这一点上放一个MessageBox,但是我只想询问版本是否过时。

我可以查询

context.Database.CompatibleWithModel(true)

找出模型是否需要升级,但我不知道如何从Configuration初始化程序中访问上下文

1 个答案:

答案 0 :(得分:0)

我使用错误处理来确定是否要求运行数据库更新。

在我的背景下,我把

public class MyAppDbContext : DbContext
{
    public MyAppDbContext(string connectionString)
        : base(connectionString)
    {
        if (!Database.Exists())

        {
            Database.SetInitializer(new MyAppDbInitializerCreateIfNotExists());
        }
        else
        {
            if (!Database.CompatibleWithModel(true))
            {
                throw new InvalidOperationException("The database is not compatible with the entity model.");
            }
        }
    }

    public MyAppDbContext() // used for migrations
        : base("name=ApplicationDatabase")
    {
        Database.SetInitializer(new MyAppDbInitializerCreateIfNotExists());
    }

    public MyAppDbContext(bool forceMigration) // used for migrations
        : base("name=ApplicationDatabase")
    {
        if (forceMigration)
        {
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyAppDbContext, Configuration>());
        }
    }

    public bool SanityCheck()
    {
        try
        {
            var rec = JobLists.Select(x => x.Id == 1);
            return true;
        }
        catch (Exception)
        {

            return false;
        }
    }

// the rest of the class
}

在我的程序中我把

 static class Program {
    [STAThread]
    static void Main() {

       /// some set up code missing here
        MyAppWindowsFormsApplication winApplication = new MyAppWindowsFormsApplication();

        try
        {
            winApplication.Setup();
            winApplication.Start();
        }

        catch (Exception e)
        {
            if (e.InnerException.Message == "The database is not compatible with the entity model.")
            {
                var msg = new StringBuilder();
                msg.AppendLine("The database structure has changed.");
                msg.AppendLine("Do you want to upgrade the database structure. (Say no and call support if you are unsure)");
                if (MessageBox.Show(msg.ToString(), "Upgrade database", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    var o = new MyAppDbContext(true);
                    o.SanityCheck();
                    MessageBox.Show("Database has been upgraded");
                }
            }
            else
            {
                  winApplication.HandleException(e); 
            }
        }
    }
相关问题