dreza dreza - 1 year ago 75
C# Question

Moving Entity framework to another project from MVC causes re-migration

I currently have an asp.net MVC 4 application which contains Entity framework 6 Code First models, DbContext and Migrations. In an attempt to separate this from my web application so I can re-use these database classes in another project I have moved all related Entity Framework classes to their own project.

However now when I run the solution it thinks my model has changed and attempts to run all my migrations once more. The problem appears to be in my use of

as if I comment out this line I can run the web application as per normal.

public static class DatabaseConfig
public static void Initialize()
System.Data.Entity.Database.SetInitializer(new MigrateDatabaseToLatestVersion<G5DataContext, Configuration>());

// make sure the database is created before SimpleMembership is initialised
using (var db = new G5DataContext())

This wasn't a problem until I've tried to move all the Entity Framework classes. Is this not possible, or have I done something fundamentally wrong?

Answer Source

At startup, EF6 queries exiting migrations in your database, as stored in the __MigrationHistory table. Part of this table is a context key, which includes the namespace of the entities.

If you move everything to a new namespace, EF6 doesn't recognize any of the previously run migrations, and tries to rebuild the database.

A quick solution is to run a script to rename the context key in the __MigrationHistory table to your new namespace. From http://jameschambers.com/2014/02/changing-the-namespace-with-entity-framework-6-0-code-first-databases/ :

UPDATE [dbo].[__MigrationHistory] 
   SET [ContextKey] = 'New_Namespace.Migrations.Configuration'
 WHERE [ContextKey] = 'Old_Namespace.Migrations.Configuration'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download