Development

Moving Entity Framework migrations to another project

This happens to me quite often, because of the way I tend to work with new projects: I’ve created a new web application, got it up and running and set up my initial code first migration, start working on the model (maybe another few migrations for new tables etc) and then realise that I want to move the database to a separate “data layer” project AFTER I’ve already started running the migrations.

So I move my Entity Framework DB context, my model POCOs and my Migrations folder out to the new project, and update all the namespaces to be right (e.g. “SiteName.Data” rather than “SiteName.Web”).

I’ll be honest, too, I don’t think I have two projects that have the same naming convention and structure, I can’t seem to decide between calling it Data, DAL, Model, or another hoist of other names and structures, so sometimes I even change it half way through and have to update my namespaces accordingly then!

What happens when you next add a new migration is that EF will try to rescaffold your entire database based on your model.

The reason is that Entity Framework doesn’t see the migrations in the __MigrationHistory table as being for this configuration. There is a column ContextKey which needs to be updated to match your new namespace structure.

For example, in my current project the original namespace for my project was SiteName.Web and my migration configuration’s namespace was SiteName.Web.Migrations.Configuration.

After moving the database layer out to the SiteName.Data project, I need to change this value in the database for all the migrations, by running a simple SQL statement:

For example:

Once that’s done, I deleted the previously attempted (incorrect) migration that had been created in my project (just delete the class file, e.g. Migrations/201607280054291_AddMyNewColumn.cs), and re-do the add-migration, and the migration correctly picks up the old migrations and works out the right delta.

You never know, though, maybe next time after having actually written all this down, I’ll remmember to split out my data layer to a separate project before running the initial migration!

You may also like
ASP.NET WebForms ScriptResource error
Developer Tip: ASP.NET Configuration in Visual Studio 2010
main-image
Mapping Shapefiles with CartoDB