(all this is due to the fact that here How does Database.SetInitializer work? (EF code, first create a database and apply migrations using several connection strings) - but everything has changed, so I think it makes sense to separate. Read it before that )
Update:
It is interesting here. I was able to reproduce the problems that you actually encountered . Here is a brief breakdown of what I think is happening:
Firstly, it worked βhappilyβ:
Database.SetInitializer(new CreateAndMigrateDatabaseInitializer<MyContext, MyProject.Migrations.Configuration>()); for (var flip = false; true; flip = !flip) { using (var db = new MyContext(flip ? "Name=MyContext" : "Name=OtherContext")) {
(I used a custom initializer from my other post that controls the migration / creation process together)
This worked great without an Initializer. As soon as I turned it on, I ran into some interesting problems.
I deleted Db-s (two, for each connection). I expected that either it would not work or it would create one db and then another in the next pass (for example, without migration, just the βCreateβ initializer).
What happened, to my surprise, did it actually create both databases on the first pass ??
Then, being a curious person :), I set breakpoints on MyContext ctor and debugged through migrator / initializer. Again empty / no db-s, etc.
He created the first instance of my call in flip . Then, at the first access to the "model", he called the initializer. The migrator occupied (did not have dB). During migrator.Update(); it actually creates MyContext (I guess through the general parameter in Configuration) - and calls the "default" empty ctor. This had a "different connection / name" by default, as well as all other Db.
So, I think it explains what you are experiencing. And why did you need to create a "Factory" to support the creation of Context. This seems to be the only way. And by setting some "AppDomain" connection string (which you actually discovered) that is not "overridden" by an empty ctor call.
The solution I see - you just need to run everything through the factory - and the 'flip' of the connection there (no need for a static connection if your factory is singleton.
It actually doesn't work at all (my test, at least) with the official MigrateDatabaseToLatestVersion initializer - and the reason I used the other.