ASP.NET Automatic Migrations

Understanding migrations can be a bit tricky. Hopefully, this article will resolve at least some of the questions you might have.

First things first - What are migrations?

Well... If you built your website using first code approach every time you change your model you need in order to keep the database in sync. There are two solutions to it; either you drop the database and recreate it or you can perform migrations.

Naturally, the first approach isn't good in the long run. Once you deploy the website online, you need to make sure that you don't lose your data. You can also modify the database by hand, but that's kind diminishing the point of the code first approach.

Using Migrations

There are various ways to perform migrations, but in order to perform any of them you need to firstly enable migrations with the following commands:

This command will enable migrations for this particular context. Make sure that the database already exsits before enabling migrations. Now, once you modify your context you need to create your migration. This is where add-migration comes into operation:

Officially, add-migration "scaffolds" a migration script for any changing data. I had to look up what the "scaffolding" is.

Scaffolding is a technique supported by some model-view-controller frameworks, in which the programmer can specify how the application database may be used. The compiler or framework uses this specification, together with pre-defined code templates, to generate the final code that the application can use to create, read, update and delete database entries, effectively treating the templates as a "scaffold" on which to build a more powerful application.

As we say in Polish: "Pouring Water", a lot of fairly meaningless sentences. Come on wiki you can do better. Or maybe it's me. It is 1 a.m. after all. Well, based on what was produced "Add-Migration" determines the changes between the current model in the database and your model in the code. In the file that is generated you will see two methods:

Simple and easy enough. Once you produce a migration you need to commit the changes to the database, before you can produce the next one. Otherwise you will get an error. Something along the lines:

Unable to generate an explicit migration because the following explicit migrations are pending: [blah_blah_blah]. Apply the pending explicit migrations before attempting to generate a new explicit migration.

So in order to commit the changes to the database we use:

And this should do the job. I have to admit this is fairly tricky. It took me 6h to get the project up and running. Different errors were occurring. In the end, I just created a new database and started from scratch.

When you publish your website, remember to select "Execute Code First Migrations".