0

I am developing window application in which DB schema can be different between each release (update view, add/remove column). Therefore I am looking for way to let EF update schema when application start up in client machine. I read some article but they point to package manager command Add-Migration, Update-Database which I can not use in my case. I used repository pattern so when I tried Database.SetInitializer<C>(new MigrateDatabaseToLatestVersion<C, Configuration<C>>()); I got Unable to update database to match the current model because there are pending changes and automatic migration is disabled. Either write the pending model changes to a code-based migration or enable automatic migration. Set DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable automatic migration. exception But when I set AutomaticMigrationsEnabled = true;I got another error: Table 'TableName' already exists.

3
  • See here and here Commented Apr 24, 2017 at 14:20
  • I already read and tried above but no success, I updated my question to have more detail @SteveGreene Commented Apr 24, 2017 at 14:35
  • Sounds like you don't have migrations properly configured. You need to make an initial baseline migration Add-Migration MyBaseline -IgnoreChanges. Then you add migrations as normal for subsequent changes. Commented Apr 24, 2017 at 15:14

1 Answer 1

0

I found a workaround, create an extension method

    public static void RunMigration(this DbContext context, DbMigration migration)
    {
        var prop = migration.GetType().GetProperty("Operations", BindingFlags.NonPublic | BindingFlags.Instance);
        if (prop != null)
        {
            IEnumerable<MigrationOperation> operations = prop.GetValue(migration) as IEnumerable<MigrationOperation>;
            var generator = new SqlServerMigrationSqlGenerator();
            var statements = generator.Generate(operations, "2008");
            foreach (MigrationStatement item in statements)
                context.Database.ExecuteSqlCommand(item.Sql);
        }
    }

And then create class MyMigration which inherit DbMigration like normal migration, and when application start, I will check and force it to run like below:

var myMigration = new MyMigration();
myMigration.Up();
this.RunMigration(myMigration);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.