Multiple DbContexts on one DB with Code First Migrations

你。 提交于 2019-11-30 14:29:36

问题


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 the suggested Solution of using one "super" context which contains all DbSet<>s and using the normal Contexts, but i got a error. ("Model backing DbContext has been changed") This is easily avoidable if you just kill the __migrationHistory table from the SQL server, but as i said, i want to keep the history.

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


回答1:


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<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 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<MyContext>());
    }
}

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.




回答2:


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



来源:https://stackoverflow.com/questions/17246069/multiple-dbcontexts-on-one-db-with-code-first-migrations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!