Entity Framework with multiple migrations and inheritance from base DbContexts within the same Database

自作多情 提交于 2019-12-10 16:44:33

问题


I'm building an extensible custom CMS solution where I have a parent DbContext named CmsDbContext with the entities for CMS tables, eg: Users table. CmsDbContext has automatic migrations enabled. I want allow the final user inherit from CmsDbContext in order to create custom extra tables/entities, by adding/mapping DbSet properties and custom POCO's.

The Cms needs that his CmsDbContext get initialized in PreStart, before the initialization of derived DbContext. So far so good, when I initialize CmsDbContext the tables are created sucessfully. When I initialize the derived DbContext e.g. CustomCmsDbContext, the extra tables are created successfully. But when the Web application is restarted, the migration process of CmsDbContext erase the tables that isn't owned by the context, and the tables for the inherited CustomDbContext are recreated.

I Know that it's possible to create multiple not related DbContexts with automatic migrations enabled within the same database, because of the ContextKey property of DbMigrationsConfiguration will. But I need inheritance here in order to allow the CustomCmsDbContext context make queries against existing tables mapped by CmsDbContext, so both contexts behaves like one DbContext, with migrations enabled.

So we know the problem is that the parent DbContext deletes tables of the child DbContext during migration process, and the child DbContext recreates the missing tables during migration process.

How to avoid migrations from deleting tables that are not owned by DbContext ?

Here is the pseudo code:

public class CmsDbContext: DbContext {

    static CmdDbContext() {
        Database.SetInitializer(new MigrateDatabaseToLatestVersion<CmsDbContext, Migrations.CmsDbContextConfiguration>());
    }

    public DbSet<User> Users { get; set; }
}


public class CustomCmdDbContext: CmsDbContext {

    static CustomCmdDbContext() {
        Database.SetInitializer(new MigrateDatabaseToLatestVersion<CustomCmdDbContext, Migrations.CustomCmdDbContext>());
    }
    public DbSet<CustomEntity> CustomEntities { get; set; }
}

回答1:


This blog post from Rowan Miller descripes a very similar scenario: Let the customer add/edit user definied columns or tables to the context.



来源:https://stackoverflow.com/questions/22943043/entity-framework-with-multiple-migrations-and-inheritance-from-base-dbcontexts-w

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