TGlatzer
TGlatzer

Reputation: 6308

Managing multiple inherited DBContexts

I'm using multiple DbContext objects in different dlls and trying to find a solution for a problem with the ModelBuilder.

Currently the Contexts are specified like this:

public class BaseContext : DBContext {
  public DbSet<EntityClass1> Entities1 { get; set; }
}

public class SpecializedContext1 : BaseContext {
  public DbSet<EntityClass2> Entities2 { get; set; }
}

public class EntityClass1 {
  public int Id { get; set; }
}

public class Entities2 {
  public int Id { get; set; }
  public virtual EntityClass1 { get; set; }
}

The context are defined in different assemblies.

If I run Add-Migation for the BaseContext everything is fine. After that I run Update-Database and the BaseContext is created in the Database.

Then I want to run the same for the SpecializedContext. This will currently not work, since the SC tries to create the tables of the BaseContext, too.

The connection strings are configured to use the same database and Update-Database access the correct one, but it always tries to add the BaseContext-Tables (and worse, if I change something in BaseContext, it tries to reflect that changes).

I tried to Ignore the classes of the BaseContext in the OnModelBuilding-Method, but this broke the ForeignKeys from the SpecializedContext.

Is there any way to tell the ModelBuilder, that BaseContext is none of it's business?

Upvotes: 1

Views: 397

Answers (1)

ctrlShiftBryan
ctrlShiftBryan

Reputation: 27760

Use Migrations on SpecializedContext only. When ever I have multiple contexts sharing tables I decide which Context needs to "own" the migrations and just use the migrations on that one.

This does mean you will need one Context that has all the tables even if it is only for migrations.

Upvotes: 1

Related Questions