Entity Framework v6 – Multiple Migrations

I love the that EF6 now allows managing migrations for multiple data contexts. This is great as it allows segregation of data tables into their own ‘domains’.

If we have a website called VideoStore, and two data contexts, one for user account details called UserAccountContext and one for a more business specific domain called VideosContext, then you can create migrations for both even if they are using the same database.

First both contexts will need a connection string in the web.config, the connections strings can point to the same database though.

Next, to enable migrations we need to run the enable-migrations command in the package manager console, and we need to include the new -ContextTypeName parameter. By default this would create the migrations directory of the root of the project, however since we have multiple we want to add the –MigrationsDirectory parameter to specify the directory for each context.

enable-migrations -ContextTypeName  UserAccountContext -MigrationsDirectory DataContexts\UserAccountMigrations
enable-migrations -ContextTypeName VideoContext -MigrationsDirectory DataContexts\VideoMigrations
Edit the configurations created and turn off automatic migrations.

Then to add a migration for the context,

add-migration -ConfigurationTypeName VideoStore.Web.DataContexts.UserAccountMigrations.Configuration "InitialCreate"
add-migration -ConfigurationTypeName VideoStore.Web.DataContexts.VideoMigrations.Configuration "InitialCreate"

Then we want to create the database:

update-database -ConfigurationTypeName VideoStore.Web.DataContexts.UserAccountMigrations.Configuration
update-database -ConfigurationTypeName VideoStore.Web.DataContexts.VideoMigrations.Configuration 

And that’s it. Super Easy.


About John

Software developer, lately specialising in Full Stack Web Development using c#, ASP.Net WebAPI 2, and Angular.
This entry was posted in Development and tagged , , , . Bookmark the permalink.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s