The Entity Framework 5 Code First Migrations mechanism works great, however there is a small issue regarding multi tenant applications where the same DbContext is used to connect to multiple databases with the same schema.
To be able to address multiple databases with the same schema, you could have two constructors:
or have a single, parameterless constructor but set the connection string after a context has been created. In both cases, the default parameterless constructor will always somehow point to a concrete, default database.
This raises following problem - the MigrateDatabaseToLatestVersion initializer creates your context using the default parameterless dbcontext constructor. It will migrate the database but only the default one! It seems that people report this issue.
To fix this, we need a modified database initializer. The initializer should migrate the current database rather than the default one. It means that the initializer should get the connection string from the current context somehow. Luckily, this is possible:
The client code is now:
Compare our new custom initializer with the existing MigrateDatabaseToLatestVersion initializer:
Differences are obvious.
The built in initializer uses reflection to create the instance of the migrations configurator and asks DbMigrator to perform the update but it doesn’t ask it for the connection to the current database! Instead, the configurator by itself creates a new instance of the DbContext using the default parameterless constructor. On the other hand, our custom initializer uses the information on the context to set the configurator’s TargetDatabase to point to a current database.
This way, multiple databases can be migrated independently.