Tel Map

Blog

Code First Migrations Entity Framework 7

Create Initial Code First Migration

In order to do Code First Migrations, you first have to set up the command dnx ef. Code first means, that you first do database model changes in the Entity Framework database classes and then apply the changes to the actual database. Please read the 2 previous blog entries about ASP .NET 5 on how to set up the dnx command line tool.

To be more specific, the examples in this article were done using Entity Framework 7 RC1. If you execute dnx ef in your ASP .NET project folder, you will get the following output.

dnx ef output:

As you can see dnx ef migrations is the command to use for adding migrations to your application.

dnx ef migrations output:

So if you have created a new DbContext from an existing database as described in my previous article or simply started coding a new DbContext, you can add your first migration with the command:

This will generate a new folder Migrations within your project including a new class file for the initial migration.

Initial Migration
Initial Migration

You can add as many migrations as you like, before actually applying them to the database.

Apply Changes to the Database

After that you can apply the migration to an existing database by using the command:

This applies all migrations you added to the database. In addition to that, it also creates a new database table __EFMigrationsHistory, which takes track of all migrations already applied to the database.

Instead of manually applying changes to the database using the command above, you can also apply all pending database changes on each application startup by executing the following command somewhere in the code e.g. in Startup.cs.

Otherwise if you use multiple databases e.g. development, production etc., you have to apply the command once for each database.

Summary

This article demonstrates how to do Code First Migrations using the Entity Framework 7. In the next article I will show how to use the new Dependency Injection that comes with ASP .NET 5 in order to inject a DbContext into a Controller.

 

Leave a Reply

Your email address will not be published. Required fields are marked *