Best practices when using Entity Framework Code First Migrations
After seeing migrations in Ruby on Rails a few years ago I regularly searched for an equivalent in the .NET space. Then finally with EF Code First Migrations were introduced. Search done!
Now, after doing two projects using Code First Migrations, here are some basic rules that you should follow1 if (and only if) you want to avoid trouble with migrations:
Use a local development database.
’nough said.
Use different seeds for different environments.
If your application requires users, your initial seed should in most cases contain an admin user to allow initial access to the application. For integration tests you should only have a bare minimum of data (just enough to get the application/integration tests running). Test-relevant data should be set up/created in your tests and cleaned before/after each test run.
Your seed method should be repeatable.
Take care that your seed method creates one time data really only once (e.g. login data for a specific user or the user itself should not be created again if it already exists). The AddOrUpdate method provides the key selector parameter for that purpose, but there may be cases where that is not enough.
Test your migrations.
The migrations generated by the
add-migration
command assume an empty database. However once you actually go live your database will not be empty. So test each migration (ideally on a copy of the live database).
Be aware of “merge” issues described in more detail in the MSDN article here.
A few ways to mitigate those are:
- Do not blindly commit your migrations. If you pull/update (depending on your SCM of choice) and you get a new migration that you do not have yet, recreate any migrations you created yourself and which are not yet committed/pushed to avoid merge issues. Take care that you roll back the migrations you are going to recreate to avoid troubles with your database.
- You can also update your model and create your migration for your changes, then immediately commit/push your changes to avoid the point above. But be aware that this approach may lead to more migrations as you make additional model changes during the implementation of a feature.
There are quite possibly more things to keep in mind, but those where the points that I remembered best. In my opinion you should follow all of those rules (with the possible exception of number 2) in any case, otherwise you and your teammates will spend some time to fix issues you will encounter when running update-database and/or deploying your application.
In my not so humble opinion that is ;-) ↩︎