Distinguishing contexts by setting the default schema
In EF6 you can have multiple contexts, just specify the name for the default database schema in the OnModelCreating
method of you DbContext
derived class (where the Fluent-API configuration is).
This will work in EF6:
public partial class CustomerModel : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("Customer");
// Fluent API configuration
}
}
This example will use "Customer" as prefix for your database tables (instead of "dbo").
More importantly it will also prefix the __MigrationHistory
table(s), e.g. Customer.__MigrationHistory
.
So you can have more than one __MigrationHistory
table in a single database, one for each context.
So the changes you make for one context will not mess with the other.
When adding the migration, specify the fully qualified name of your configuration class (derived from DbMigrationsConfiguration
) as parameter in the add-migration
command:
add-migration NAME_OF_MIGRATION -ConfigurationTypeName FULLY_QUALIFIED_NAME_OF_CONFIGURATION_CLASS
A short word on the context key
According to this MSDN article "Chapter - Multiple Models Targeting the Same Database" EF 6 would probably handle the situation even if only one MigrationHistory
table existed, because in the table there is a ContextKey column to distinguish the migrations.
However I prefer having more than one MigrationHistory
table by specifying the default schema like explained above.
Using separate migration folders
In such a scenario you might also want to work with different "Migration" folders in you project. You can set up your DbMigrationsConfiguration
derived class accordingly using the MigrationsDirectory
property:
internal sealed class ConfigurationA : DbMigrationsConfiguration
{
public ConfigurationA()
{
AutomaticMigrationsEnabled = false;
MigrationsDirectory = @"Migrations\ModelA";
}
}
internal sealed class ConfigurationB : DbMigrationsConfiguration
{
public ConfigurationB()
{
AutomaticMigrationsEnabled = false;
MigrationsDirectory = @"Migrations\ModelB";
}
}
Summary
All in all, you can say that everything is cleanly separated: Contexts, Migration folders in the project and tables in the database.
I would choose such a solution, if there are groups of entities which are part of a bigger topic, but are not related (via foreign keys) to one another.
If the groups of entities do not have anything to do which each other, I would created a separate database for each of them and also access them in different projects, probably with one single context in each project.