Multiple DbContexts on one DB with Code First Migrations

前端 未结 2 984
南笙
南笙 2021-01-01 06:43

I stumbled uppon the same problem as described in this question. In addition, i didn\'t want to loose the __migrationHistory table from the database.

I tried it with

2条回答
  •  清歌不尽
    2021-01-01 07:08

    First, you have to create a "Super" Context for the Migrations 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());
        }
    }
    

    Then just create the following class:

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

    now, in every small Context you have, 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());
        }
    }
    

    now you won't get this error any more,
    plus, you will have your migration-History,
    and you will use multiple Contexts on one Database.

提交回复
热议问题