[1.7.x] Fixed #22823 (and partly #22563) - FKs from unmigrated apps breaking state.

Thanks to bendavis78 for the test and diagnostic work.