I have been working with EF Code First Migrations for a while but until recently had not used it for updating more than a local development database. As I discovered, it is actually pretty easy to run your migrations against different databases. The update-database command has an optional switch for a ConnectionStringName. However, if you are using web.config transformations to manage connection strings for different environments, you may only have one connection string name, with the environment specific connection string being defined in each transform. I’ll explain how I am getting around that.
To run migrations against your local database, you can run the following command in the Package Manager Console. The –project switch is optional. It is only needed in cases where you have the EF context, models etc defined in a different project than your web application.
1: update-database -project "project-name-with-migrations"
To get around the single connection string problem, the simplest solution I found was to create separate named connection string in the base web.config file. So for example in the web.config connectionString section you would have:
2: <add name="development" connectionString="..." />
3: <add name="test" connectionString="..." />
4: <add name="production" connectionString="..." />
This would enable migrations to be run in test with
1: update-database -ConnectionStringName="test"
Yes – this does introduce duplication, since the “test” connection string is also defined in web.test.config. But to me this is worth the tradeoff of being able to update databases in different environments without having to use an additional tool to sync database schemas.
If I find a better workaround I will post an update, but for now this does the job.