Entity Framework with multiple migrations and inhe

2019-06-24 17:49发布

问题:

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.