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):

this.AlterColumn("Reviews", "TwoWordReview", c => c.String(maxLength: 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:

Update-Database -TARGETMIGRATION:$InitialDatabase 
-StartUpProjectName "ToTheCloud.Infrastructure"
-ConnectionString "Server=tcp:<server_name>.database.windows.net,1433;Database=<database_name>;User ID=<db_user_name>@<server_name>;Password=;Trusted_Connection=False;Encrypt=True;MultipleActiveResultSets=True;Max Pool Size=100;"
-ConnectionProviderName "System.Data.SqlClient

 For example to connect to an Azure site:

update-database -ConnectionString "Data Source=tcp:<YOURSQLSERVER>,1433;Initial Catalog=<DATABASE>;User Id=<USERID>;Password=<PASSWORD>;" -ConnectionProviderName "System.Data.SqlClient