Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
727 views
in Technique[技术] by (71.8m points)

entity framework 4 - EF 4.3 Auto-Migrations with multiple DbContexts in one database

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...