Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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; }
}
like image 855
Jone Polvora Avatar asked Apr 08 '14 16:04

Jone Polvora


1 Answers

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

like image 116
user3411327 Avatar answered Sep 22 '22 05:09

user3411327