How to add a new foreign key property to existing data in EF core?

Viewed 788

How do you add a new foreign key property to existing data in EF Core?

Say you have some models, you create a new model which will have a foreign key to one of your existing models.

add-migration will fail because the existing records won't have the foreign key. What is the right approach to solving this?

1 Answers

I was in this situation before and I found 2 possible scenarios.

Scenario one.

If you plan to update the existing data after the changes apply than you can do this in a couple steps:

  1. Create the initial FK and configure it as nullable.
  2. Do the migration.
  3. Update the existing rows with a value for the FK.
  4. Reconfigure the property and set it as required.
  5. Do the final migration.

Scenario two. (This one I like more)

You can add in the new table the value as "N/A" for example and than update all the existing rows during the migration with this value.

  1. Configure the new model and make sure you add also some initial data using .HasData() extension.
  2. Run the migration.
  3. Add and configure the property in the existing model with a default value. Example ID = 1 would be for "N/A" in the new table.
  4. Run the second migration.

I'm not entirely sure that this would qualify as a "best practice" but it did the trick for every single time.

Related