Back to all posts

Handling Namespace and Class Changes in Entity Framework

Posted on Oct 08, 2015

Posted in category:
Development
Entity Framework

Entity Framework is an amazing set of tooling that helps to manage data access in an efficient manner, however, it seems that when things start to go "funny" it can be a major time-suck. A recent issue that I experienced that I thought would be worth sharing was an issue related to applying migrations. Adding migrations is something that has become trivial, yet one day my project reported "Unable to generate an explicit migration because the following explicit migrations are pending:...." With every single one of my existing migrations listed. This was highly curious, as the application has been in use, in production, for the better part of a few months.

Digging In

The first step in my review of the issue was to look at the __MigrationHistory table in the target database to see if records were reported. You can use the simple query below to obtain this information.

List Migrations
SELECT MigrationId, ContextKey, Model, ProductVersion
FROM dbo.__MigrationHistory

The key with this query is that the "MigrationId" is the name of the migration that you created when initially defining the migration. In the case of my application, all migrations were listed, as I had suspected.

The Problem

So, with all of the migrations listed, and the database current, why couldn't Entity Framework see them? Well, a few weeks prior, I completed a re-structure of the project, changing the namespace of the project from "AirTrackData" to "FlightFiles.Data." This changed the namespace that pointed to the migration. As such, Entity Framework, when looking for applied migrations it looks at the combination of "MigrationId" and "ContextKey." The ContextKey, is simply the namespace to the migration configuration for your project. To fix my issue I simply executed the below query.

Fix Namespace
UPDATE dbo.__MigrationHistory
SET ContextKey = 'FlightFiles.Data.Migrations.Configuration'
WHERE ContextKey = 'AirTrackData.Migrations.Configuration'

Lesson Learned

This issue was a bit more confusing than expected as the application actually ran completely fine, it was only at the time of applying an additional migration that the issue was countered. A key command to help diagnose the initial issue, as well as to validate the effectiveness of the final fix is the "Get-Migrations" command. This lists all migrations that have been applied to the current database context. Very helpful!.

Happy coding! Hope this helps someone else out!