EF 4.3 Auto-Migrations with multiple DbContexts in one database

Joachim Rosskopf picture Joachim Rosskopf · Feb 2, 2012 · Viewed 12.3k times · Source

I'm trying to use EF 4.3 migrations with multiple code-first DbContexts. My application is separated into several plugins, which possibly have their own DbContext regarding their domain. The application should use one single sql-database.

When I try to auto migrate the contexts in an empty database, this is only successful for the first context. Every other context needs the AutomaticMigrationDataLossAllowed-Property set to true but then tries to drop the tables of the previous one.

So my question is:

  • How can I tell the migration-configuration just to look after the tables defined in their corresponding context and leave all others alone?
  • What is the right workflow to deal with multiple DbContexts with auto-migration in a single database?

Thank you!

Answer

Anuj Pandey picture Anuj Pandey · Apr 4, 2012

Here is what you can do. very simple.

You can create Configration Class for each of your context. e.g

internal sealed class Configuration1 : DbMigrationsConfiguration<Context1>{
   public Configuration1 (){
        AutomaticMigrationsEnabled = false;
        MigrationsNamespace = "YourProject.Models.ContextNamespace1";
   }
}

internal sealed class Configuration2 : DbMigrationsConfiguration<Context2>{
   public Configuration2 (){
        AutomaticMigrationsEnabled = false;
        MigrationsNamespace = "YourProject.Models.ContextNamespace2";
   }
}

Now you add migration. You dont need to enable migration since you already did with the 2 classed above.

Add-Migration -configuration Configuration1 Context1Init

This will create migration script for context1. your can repeat this again for other Contexts.

Add-Migration -configuration Configuration2 Context2Init

To Update your database

Update-Database -configuration Configuration1
Update-Database -configuration Configuration2

This can be done in any order. Except you need to make sure each configration is called in sequence.