Articles in categories

Articles

Entity Framework with multiple Db contexts

Entity Framework 6 added support for multiple DbContexts by adding the -ContextTypeName and -MigrationsDirectory flags. If you have 2 DbContexts in your project and you run enable-migrations, you'll get an error:

PM> enable-migrations
More than one context type was found in the assembly 'MembershipManager.EntityFramework'.
To enable migrations for 'MembershipManager.EntityFramework.Context.ApplicationDbContext', use Enable-Migrations -ContextTypeName MembershipManager.EntityFramework.Context.ApplicationDbContext.
To enable migrations for 'MembershipManager.EntityFramework.Context.MembershipManagerDbContext', use Enable-Migrations -ContextTypeName MembershipManager.EntityFramework.Context.MembershipManagerDbContext.

So you have to run enable-migrations on each DbContext separately. And you have to specify a folder for each Configuration.cs file to be generated...

PM> Enable-Migrations -ContextTypeName ApplicationDbContext -MigrationsDirectory Migrations\ApplicationDbContext

PM> Enable-Migrations -ContextTypeName MembershipManagerDbContext -MigrationsDirectory Migrations\MembershipManagerDbContext

 

To add migrations for each DbContext, you do it like this by specifying the fully qualified name of the Configuration class:

 PM> Add-Migration -ConfigurationTypeName MembershipManager.EntityFramework.Migrations.ApplicationDbContext.Configuration "M001"

PM> Add-Migration -ConfigurationTypeName MembershipManager.EntityFramework.Migrations.MembershipManagerDbContext.Configuration "M001"

 

And you run update-database the same way:

PM> Update-Database -ConfigurationTypeName MembershipManager.EntityFramework.Migrations.ApplicationDbContext.Configuration

PM> Update-Database -ConfigurationTypeName MembershipManager.EntityFramework.Migrations.MembershipManagerDbContext.Configuration

 

Revert migration:

PM> Update-Database -ConfigurationTypeName MembershipManager.EntityFramework.Migrations.MembershipManagerDbContext.Configuration –Target MigrationNameToRevertTo (e.g. => 201605061241241_Initial)