Basic Entity Framework Migrations

Entity Framework supports a code-first approach with migration support.  This article covers what I learned using EF and Migration for a new project.  This project resulted in a base ASP.NET MVC4 framework I can use as a boilerplate for multiple projects.  The boilerplate project can be downloaded from my GitHub repository.  The repository is easy to use.  Simply do a fulltext search and replace for “Stub” with “YourProjectName”. 

You also need a database, for simplicity, I assume you have SQL server (Express or other) installed as the default instance.  You can use a named instance but you’ll need to to update all the app.config and web.config files.

BaseMVC4EFWebSite

This site template contains the following:

  • .NET 4.5
  • ASP.NET 4
  • EntityFramework 5
  • CodeFirst with Migrations enabled

Using the migrations support is rather easy.

  1. Update your models as needed
  2. Open the Package Manager Console (Tools->Library Package Manager -> Package Manager Console)
  3. Select the DataAccess project in the “Default Project” dropdown
  4. In the console window, enter “update-database”

This will add any new tables or columns in your database.

If you make changes to existing tables (max column width, for example) or data, you need to use Migrations.  The process is similar

  1. Update your models.
  2. In the Package Manager Console window enter, add-migration <some useful name>. For example “add-migration widen-columns”
  3. This creates a migration class with the Up and Down methods.
  4. These methods must be updated to perform the changes you want.

For example, to widen the colum Reviews.TwoWordReview to 300 characters or nvarchar(300):

  1. In the console window, enter “update-database”

 Making the changes on a remote server is also easy.  Use the following command in the package manager console:

 For example to connect to an Azure site:

Share this Post