Nov 25, 2016
In today's blog I will show you how to use Code First Migrations to update the schema of a database when the model classes in Entity Framework change.
If you are using the Database First approach the model can be easily updated whenever changes happen in the backend database schema by just using the context menu of the Model Designer and selecting the command to update the model. All the code is automatically maintained by a tool. But in the Code First approach you start with the model classes and the Database is generated from there. If afterwards you add properties to a model class or simply add/remove a whole model class and try to run the application again then you will get an InvalidOperationException telling you that the model backing the context has changed since the database was created. In this scenario Code First Migrations comes to the rescue. Let's see the details of how to use it.
First you open the Package Manager Console from the Tools | Library Package Manager menu. This console is essentially a PowerShell console. You typically opens it to install/upgrade NuGet packages, but in here you will run commands that support the Code First Migrations feature.
Now run the command Enable-Migrations in the console. This will add a Migrations folder to your project with two classes: the Configuration class and the InitialCreate migration class. In most cases you don't need to change the default settings in the Configuration class. The code in the InitialCreate class represents the objects that have already been created in the database.
After migrations were enabled you can now make the necessary changes in the model as for example adding or removing properties in existing model classes.
Now go back to the Package Manager console and run the command Add-Migration passing as the only parameter a suitable name for the migration. This will add a class to the Migrations folder with the code representing the changes that need to be done in the database to back the current model.
The final step is to apply the migration to the database by running the command Update-Database. If all we want is to apply the latest migration we don't need to pass any parameters. If you have already applied a certain number of migrations we can revert the database schema to the state after a particular migration by passing the name of the migration to the flag -TargetMigration.
Sometimes you may not want to modify the database immediately but just generate a sql script with the required modifications and then send that script to the DBA. To achieve that all it takes is use the flag -Script. The script will be created and opened in Visual Studio, and you can save it for later use.
There are some customisations you can apply to the above procedure, but we will leave it for a later blog.
For more information, take a look at our course 20486 - Developing ASP.NET MVC 4 Web Applications.