Karan
Karan

Reputation: 15104

Continuous Integration with EF Code First Migrations

I was wondering if I could automate completely code first migrations for continuous integration.

Currently my continuous integration simply simply updates the code changes, however, I manually generate a migration, and update the database on my continuous integration server.

Is it reliable / possible / recommended to generate the migrations and update the database automatically?

For example:

I have user with property userId and username. I then add a property age into the code. Current scenario would require me to create a migration that will capture this change, and then I check in my changes to the version control. The continuous integration will spot this change, and will deploy the new version. I have to manually update-database (which should be automated).

Can I skip out the generation of migration too, such that I can simply add the property age onto the code, and the continuous integration will generate this migration. Not sure if this is recommended.

Upvotes: 20

Views: 4298

Answers (2)

Jiri Klouda
Jiri Klouda

Reputation: 1370

Part of continuous integration is also possibility of rolling back bad changes if they don't pass the tests.

  • Do you write your database upgrade scripts in a way they can be also downgraded?
  • Do you create some save-points or backups for each commit?
  • Would you lose data in the database in case of backup/restores on bad commits?
  • What is bad change is in the DDL itself?

Those are some of the questions you should think about before implementing it.

Upvotes: 0

RMD
RMD

Reputation: 3253

The answer is yes, but not quite how you're describing.

You must and should manually generate the migration. Not all migrations can be created automatically, and in those cases, manually modification of the generated migration is necessary. Column splits, certain types of data type changes, etc.

Your CI server can then leverage migrate.exe to get your databases synced up with your model. The tricky part is handling migrations that result in downgrades. So going from v1 to v2 is easy, but from v2 back to v1 is trickier as only the v2 assembly knows how to get "back" to v1.

I ended up creating a custom tool that executed migrations intelligently and automatically determined which model (context) assembly to use for the migration. You can get an idea of how to do that here: EF Code First Migrations to Deploy Older Version

The end result is that I can check in a model change / migration and know that my db change will be deployed automatically to any environment that's part of my ci/cd pipeline - and yes, that absolutely includes production.

Upvotes: 7

Related Questions