سؤال

I am using an EF code first generated database which provides some seed data, and imported data from other databases (ten thousands of rows, so it doesn't make sense to seed in EF). In an effort to streamline the process I figured I could just script the entire database's data only. So if I ever need to DropCreate (right now we use Migration strategy) my database again I can seed all my data at once.

However, the script generated by SQL Server causes tons of these conflicts:

The INSERT statement conflicted with the FOREIGN KEY constraint...

I can imagine this is because our data is very complex and inserting the data in the wrong order can cause this. Is there some way I can get the .sql script to ignore/turn off all foreign key constraints for the database before populating the tables, but then turn them back on after insertion is complete? There should be no constraint issues once all the data is inserted.

هل كانت مفيدة؟

المحلول

Yes, you can temporarily disable foreign keys :

ALTER TABLE MyTable NOCHECK CONSTRAINT FK_MyTable_MyKey

When you reenable the constraint, you should check the constraints to ensure there are no violations, like so (Note the double CHECK CHECK)

ALTER TABLE [MyTable] WITH CHECK CHECK CONSTRAINT FK_MyTable_MyKey

See this post for a database-level solution.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top