Toggle Menu

Insights > Tech Tips > What Is An Entity Framework Code First Migration?

What Is An Entity Framework Code First Migration?

Update: Readers in the Washington, DC area can learn more about this topic at Shahed’s upcoming presentation in Maryland: When: Wednesday Oct 23, 2013 @ 6:30PM EST. Event: BaltoMSDN (Baltimore Area Microsoft Developer User Group), Baltimore, MD. Topic: Entity Framework Code First Migrations. [updated post below] One of our Consultants, Shahed Chowdhuri, gave a great talk about Entity Framework Code First Migrations that […]

By

October 11, 2013

Update: Readers in the Washington, DC area can learn more about this topic at Shahed’s upcoming presentation in Maryland:

[updated post below]

One of our Consultants, Shahed Chowdhuri, gave a great talk about Entity Framework Code First Migrations that we thought our readers could learn from.  The following post is an excerpt from his blog about his talk on the Data Layer of an enterprise web application.

So what the heck are Code First Migrations and how are they helpful?  Read on to find out!

Shameless Plug: Shahed first presented this material at the Northern Virginia (NoVA) CodeCamp for Spring 2013.  This talk was part of a larger presentation about Lean Enterprise Architecture, which includes the Domain Layer from a fellow Excellian, Sahil.  To round out the content, a third talk on the Presentation Layer was given by Doguhan, another Excellian.  NoVA CodeCamp is a great way to meet other software developers in the area, and provides plenty of great learning opportunities for code junkies (like us).

Options & Alternatives

Here are a few options you have when modeling your entities for an enterprise web application:

What Problems Are We Trying To Solve?

When modeling your data, you may have conflicts within your development team, with other development teams, and also with enterprise architects at your organization.  With Migrations, you will have the opportunity to get everyone on the same page.

When you make add a new field or a new entity, you want to be sure that everyone else has it too.  When your application is deployed onto various server environments (e.g. Testing, Mock and Production), you need to know that that all the corresponding databases are on the same version.

A Simple Example

Download the sample project from Wake Up And Code!

Open the PatientRecords.sln file in VS2012 and you will observe the following:

First, let’s discuss the PatientRecordsDbContext class in the Models subfolder:

Next, let’s take a look at the Human class, also in the Models subfolder

On to the Mapping subfolder:

Now, expand the PatientRecords web project:

Finally, Migrations!

In order to use Code First Migrations, download the project exercise (from Wake Up And Code!), without migrations added to it.  Make sure you enable Nuget Package Restore to restore all packages (e.g. EntityFramework) and restart your project after the restoration.

You will go through the following steps:

  1. Enable Migrations.
  2. Create initial migration and auto-generate database.
  3. Make model changes in your code.
  4. Add a new migration for model changes.
  5. Update your database for your new migration.

All migrations commands are run from the Package Manager Console.  If you don’t have this panel open in VS2012, click on Tools -> Library Package Manager -> Package Manager Console.

1.  Enable Migrations

In order to enable migrations, select the DAL project as the default project in the PMC, then run the following command.

> Enable-Migrations -ContextTypeName Dal.Models.PatientRecordsDbContext

In the Migrations subfolder, a Configuration.cs file was automatically created, including a Seed method.  You may update the Seed method to include lookup/reference data for your database, using the DbContext that is passed on to the method.

2.  Create initial migration and auto-generate database.

To create the initial migration (and generate the database), run the Add-Migration command, followed by a name for this migration, e.g. “InitialCreate”.

> Add-Migration "InitialCreate"

This will create a new Migration file that contains the necessary commands to create the Human table.

Run the Update-Database command to auto-generate an mdf file under App_Data in the web project. (The database file won’t be attached to the web project by default.)

> Update-Database
3.  Make model changes in your code

Add a middle name to the Human class, and rebuild your solution.

public string MiddleName { get; set; }
4.  Add a new migration for model changes

Run the Add-Migration command, followed by a name for the migration, “AddedMiddleName”.

> Add-Migration "AddedMiddleName"

This will create a new migration with a filename that includes the above name.  It should be visible in the Migrations subfolder, prefixed by a timestamp.

5.  Update your database for your new migration

The database has not been updated at this point.  To do that, run the Update-Database command.

> Update-Database

Running this command automatically updates the Humans table with a new MiddleName field, and also runs the Seed method to insert the sample records.  If we run the Update-Database command again, it won’t have any more database updates to run, but it will still run the Seed method each time.

Making Migrations Work
  1. Before you add a migration, you should discuss your upcoming changes with your dev team.
  2. Inspect your migration code, and make additional changes as necessary (e.g. provide explicit names for constraints if required by your organization’s enterprise architects).
  3. After you’ve added a migration, you should update your database to test it out.  After verifying that everything works, push your code so that other developers may pull and update their own database.
  4. For server deployments, run migrate.exe against your deployed application on the web server.  This executable is available under the Tools subfolder for EntityFramework in your NuGet packages.  This step can be automated during web server deployments, so that the corresponding database are also updated as necessary (For table alterations, you must make sure that you’re not wiping out any data unintentionally).
 Trouble with Package Manager commands?

Try the following after downloading each sample:

  1. Delete your Packages folder first.
  2. Open .sln in VS2012.
  3. Restore NuGet Packages when prompted.
  4. Clean Solution.
  5. Uninstall EF via NuGet.
  6. Reinstall EF via NuGet.
  7. Rebuild your solution.

Reference: http://stackoverflow.com/questions/10999561/exception-raised-when-im-trying-enable-migrations-in-ef-4-3-1

If you enjoyed this post and want to read others like it by Shahed, please visit his blog Wake Up And Code!  If you have a question about this topic or have something interesting to share from the NoVA CodeCamp, please leave your comments below!

You Might Also Like

Tech Tips

Top Four Highlights from .Net Core 2.1

.Net Core 2.1 was announced recently by Microsoft along with corresponding updates for ASP.Net Core...

Tech Tips

NancyFX Vs. Web API in ASP.Net Core

In my previous post, I gave an overview of NancyFX, an open source and community...

Tech Tips

Getting Started NancyFX and ASP.Net Core

Many people will start a new ASP.Net Core project and choose Web API as their...