Multiple DbContexts on the same database with the first code migration

I came across the same problem that I described in this question . In addition, I did not want to lose the __migrationHistory table from the database.

I tried this with the proposed solution to use one "super" context, which contains all the DbSet <> s and uses the usual Contexts, but I got an error. ("The replica of the DbContext model has been changed") This can easily be avoided if you just killed the __migrationHistory table from the SQL server, but, as I said, I want to keep the history.

I found a simple and simple solution, see my answer below.

+3
source share
2 answers

First you need to create a “Super” context for the migration configuration.

MySuperContext : DbContext { // All DbSet<> s from your different contexts have to be referenced here once, you will only use this class for the migrations. public MySuperContext() : base("YourConnectionString") { System.Data.Entity.Database.SetInitializer(new MigrateDatabaseToLatestVersion<MySuperContext, MyMigrationsConfiguration>()); } } 

Then just create the following class:

 public class NoDatabaseInitializer<T> : IDatabaseInitializer<T> where T: DbContext { public void InitializeDatabase(T context) { // Do nothing, thats the sense of it! } } 

now, in each small Context, you add this to the constructor:

 class MyUserContext : DbContext { public MyUserContext : base("MyConnectionString") // Can be a user context, etc { System.Data.Entity.Database.SetInitializer(new NoDatabaseInitializer<MyContext>()); } } 

now you will no longer get this error,
plus, you will have your migration history,
and you will use several contexts in one database.

+3
source

EF6 supports multiple DbContext for each database: http://entityframework.codeplex.com/wikipage?title=Multi-tenant%20Migrations

+2
source

Source: https://habr.com/ru/post/1201625/


All Articles