Posted by Anuraj on Saturday, February 20, 2016
This post is about Entity Framework 7 Code First Migrations. Code First Migrations is a Entity Framework feature which helps to apply database schema changes without re-creating the whole database. In ASP.NET 5, Microsoft released EF 7, which helps to run migrations with dnx command.
For enabling the code first migrations, you need to modify the project.json file and add the reference of EntityFramework package references and commands. Here is the project.json file.
Now you can try EF commands using dnx ef command, which will display EF screen like this.
Here is the model class and database context class.
Now you can run the ef commands to create migrations.
This command will create a Migrations folder and will display result like this.
Now you can run the code to create the database.
Migration name is optional, if not specified, all the pending migrations will be applied. Once migrations completed, it will create the database and display a message like this.
You can add code to use the database. This code will create an entry into the blog table.
Now you can modify the model class. A Url property added to the blog class.
If you run the application, you will get a DbUpdateException. Now you can add one more migration and update the database.
Now you need to create another migration and need to update the database again.
Similar to Initial migration, it will create classes under Migrations folder. You can view the Migrations using list command like this.
And it will display something like this.
Now if you run the application using dnx run, you won’t see the DbUpdateException any more. Now let’s add one more class, and customize the database update.
Here is the post class and blog class also modified to enable relationship.
Now you can create another migration for the Post class.
We are making the title column as unique and rating column’s (new coloumn in blog class) default value as 3. You can open the PostClassAdded postfix file and modify the code. Here is the updated code, Rating default value set to 3 and Post title unique constraint added.
Now if you run the database update, the database will be modified with new table and columns. Using EF migrations you can create SQL Scripts as well, which helps to share to the Database team if required. You can do that using script command.
It will print the generated SQL Script into the console. Like this
If you want to generate it file, you can use -o option, where you can specify the output file.
Happy Programming :)