How to apply entity framework migrations that add required foreign key columns to an existing database?

Viewed 42

I'm working with a C# library called IdentityServer4. It has its own set of Entity Framework DbContext objects. Each time a new release of IdentityServer4 comes out, you're supposed to create a new Entity Framework migration and apply it to your database.

I've created the migration. The migration contains many new columns including foreign keys that require a valid reference.

When applying this migration to my existing database, which has a lot of data already in it, the migration fails to apply because those new columns do not have data and therefor break the foreign key relation requirement.

Does entity framework have a recommended strategy for approaching this type of migration application? I can't just delete all of the data while I apply the migration.

How can I get these new columns applied using the entity framework migration?

1 Answers

Typically you provide a reasonable default value. If that's not possible, you might have to edit these model objects to be less strict, then create another migration that gives you a reasonable default (or creates these objects) then another migration to bring the model up to compatibility with the latest release of IdentityServer4

Edit:

  1. The essential process I would follow is to create the migration (but don't apply it yet)

  2. Edit the migration that is created to generate it without the foreign keys and use nullable fields

  3. Create another empty migration and edit it to use some SQL to add valid values to the affected fields

  4. Add another migration (perhaps starting with an empty one) and add the migration code to bring it up to the current IdentityServer model spec by changing the fields to non-nullable and adding the foreign keys.

This is a tedious process with some trial and error, so keep a backup of the database and if you have multiple databases that are using this application (like several customers or test databases) also keep some backups of these and try this method on those as well until you're comfortable that it works well before deploying/releasing the code.

Related