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.
1 Answer
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);
Add-Migration MyBaseline -IgnoreChanges. Then you add migrations as normal for subsequent changes.