1

Once FK Constraints have been created via Entity Framework Core 1.1 with Migrations in an ASP.NET Core Code First app, would it be ok to temporarily enable/disable the constraints directly in SQL Server without using EF - would it break the migrations created via EF etc? Background: I need to truncate data from a table that has been referenced by several tables via FK's that were created through EF Code First. SQL Server, as expected, complains that you can truncate the table since it's been referenced by a FK etc.

nam
  • 21,967
  • 37
  • 158
  • 332
  • You can also add a SQL script to your migrations file. This way you would have more flexibility. – Ignas Aug 10 '17 at 14:18
  • @lgnas How do we do that? – nam Aug 10 '17 at 14:28
  • For example: https://stackoverflow.com/questions/26535189/entity-framework-execute-sql-before-migrations – Ignas Aug 10 '17 at 14:38
  • 1
    If you are just temporarily disabling constraint to truncate the data (and also making sure that all referenced data is also removed else database will end up in inconsistent state) then after re-enabling them migrations will be just fine. As long as you are putting database in same state as before in terms of objects managed by EF & the data is in consistent state, it is fine. – Smit Aug 11 '17 at 22:43
  • @Smit Thanks. That's what I needed to know. – nam Aug 11 '17 at 22:50

2 Answers2

1

No, it would not break migrations. If you are doing anything on database and then reverting back the schema design of database to earlier state then migration will just run fine. Migrations when applied expect that shape of EF managed objects in database to be remain same (as it would have known earlier). Any temporary change is invisible to migration. And state needs to be same afterwards because when future migrations applied then appropriate objects are present otherwise DDL can cause failure.

Smit
  • 2,279
  • 1
  • 12
  • 22
0

Anything you change in the database schema in SQL Server, without the code, will break the migrations. You should delete the foreign key references in the code for the operation you want to do and then recreate them later. Though, be careful, if your data is left in inconsistent state, you might not be able to recreate constraints without losing data.

tech-y
  • 1,829
  • 2
  • 16
  • 26
  • I'm not changing the schema, i.e not dropping the constraints just disabling them temporarily. – nam Aug 10 '17 at 14:38
  • Still, it will use the command "ALTER TABLE TableName NOCHECK CONSTRAINT ConstraintName" internally, thus, it will break the migration. – tech-y Aug 10 '17 at 14:48
  • Since I'm disabling them `temporarily` I will enable them back – nam Aug 10 '17 at 14:58