Fragment Fragment - 9 days ago 5
C# Question

Code First migration. Check if foreignKey exists before calling DropForeignKey

My project is based on the code-first approach.

I have a customly declared migration, with declared Up and Down methods (to fix previously merged branches issues in my project).

After that i tried several times to rollback and to apply my custom migration, - all works fine.

But during teamCity project compiling, it throws an error, because it works with migrations differently, than visual studio, and it tries to rollback Up method, drop unexistent constraints, but i have different foreign keys in Up and Down methods.

How can i check if foreignKey exists before trying to execute DropForeignKey(...)?

Answer

Exploring this assumption, i figured out, that problem was in incorrect implementation of foreign key between entities. And in my case, incorrect migrations already has been deployed to production, so my solution was:

  • Generated rollback script to a valid migration with all incorrect migrations (in Package Manager Console this is command: Update-Database -TargetMigration: -Script)

  • Rolled back to a valid migration, and generated new correct migration script.

Comments