EF Code-Based Migrations

Sharing schema changes to a database is a big challenge when working on an application. In the past, people would write SQL change scripts, check them into the code, and then have to tell everyone which scripts they need to run. It also required a lot of bookkeeping to know which of these scripts had to be run against the production database when the next version of the application was deployed.

EF Code-Based Migrations is a code-driven, structured way of making changes to the database and is included in Entity Framework 4.3 and above.

Although I won't cover all the details of Migrations here, I will cover some of the ways we make use of migrations. Expand the Migrations folder to see the list of migrations included in the NuGet Gallery, as shown in Figure 16.8. The migrations are named with a timestamp prefix to ensure they run in order.

The one named 201110060711357_Initial.cs is the starting point. This file creates the initial set of tables. After that, each migration applies schema changes as we develop the site and make changes.

Use the NuGet Package Manager Console to create migrations. For example, suppose I add a property named Age to the User class. I can open up the Package Manager Console and run the following command:

Add-Migration AddAgeToUser

Add-Migration is the command to add a new migration, and AddAgeToUser is the name of ...

Get Professional ASP.NET MVC 4 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.