Merging Entity Framework Code First Migrations - Entity Framework Code First

Overview

Entity Framework Code First Migrations work well when you are a single developer working on an application, and in a team environment if only one person is making changes to the model. Issues arise when multiple developers make changes to the model at the same time. Common error messages include the following.


This article outlines two options for resolving these situations.

Reference

This article was adapted from https://msdn.microsoft.com/en-us/library/dn481501(v=vs.113).aspx

Assumptions

1. You have no pending model changes. That is, all model changes have been captured in a Code First Migration.

2. You have synchronized your code with source code control.

Option 1: Add a Blank Merge Migration

1. Run add-migration MigrationName -ignorechanges — for example: add-migration Merge -ignorechanges. This (1) generates an empty migration and (2) captures a snapshot of the current model in the resource file for the migration.

2. Run update-database.

Option 2: Update the Model Snapshot in the Last Migration

This second option is a little harder and can’t be used in every scenario, but it’s also cleaner because it doesn’t involve adding an extra migration. This approach is only feasible if the latest migration exists only in your local code base and has not yet been submitted to source control (i.e. the last migration was generated by the user doing the merge)

1. Run update-database -targetmigration SecondLastMigration.

2. Run add-migration FullNameOfLastMigrationIncludingTimestamp. You need to include the timestamp in the name so that Code First Migrations knows you want to edit the existing migration rather than scaffolding a new one. This will update the metadata for the last migration to match the current model.

3. Run update-database