多个DbContexts在一个数据库与代码优先迁移 [英] Multiple DbContexts on one DB with Code First Migrations
问题描述
我偶然发现了与这个问题。此外,我不想从数据库中删除__migrationHistory表。
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.
我尝试使用一个使用一个超级上下文的解决方案,其中包含所有DbSet< ;> s并使用正常的Contexts,但我有一个错误。 (模型支持DbContext已被更改)
如果您只是从SQL服务器中删除__migrationHistory表,但是正如我所说,我想保留历史记录,这很容易避免。
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.
推荐答案
首先,你必须为迁移配置创建一个超级上下文。
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>());
}
}
然后只需创建以下类:
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>());
}
}
现在你不会再收到这个错误,
plus,您将拥有您的迁移历史记录,
,您将在一个数据库中使用多个上下文。
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.
这篇关于多个DbContexts在一个数据库与代码优先迁移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!