public IEnumerable <object> GetClearDataCommands() { var commands = new List <object>(); ICollection <string> remainingTables = this.tables.ToList(); var remainingRelationships = new RelationCollection(this.relations); var safetyNet = 0; var max = this.tables.Count() * 3; while (safetyNet++ <= max) { var referencedTables = remainingRelationships.GetReferencedTables(); var leafTables = remainingTables.Except(referencedTables).ToList(); if (leafTables.Any() || !referencedTables.Any()) { commands.AddRange(leafTables.Select(t => new ClearTableCommand(t))); if (!referencedTables.Any()) { return(commands); } remainingTables = remainingTables.Except(leafTables).ToList(); remainingRelationships = remainingRelationships.WithoutLeaves(leafTables); } else { var nullableRelation = remainingRelationships.FindFirstNullableCyclicRelation(); if (nullableRelation == null) { throw new InvalidOperationException("Cylclic foreign key detected with no nullable foreign keys"); } commands.Add(new NullColumnCommand(nullableRelation.SourceTable, nullableRelation.SourceColumn)); remainingRelationships = remainingRelationships.WithoutRelation(nullableRelation); } } throw new InvalidOperationException("Infinite loop detected whilst processing tables: " + Environment.NewLine + Environment.NewLine + string.Join(Environment.NewLine, this.tables) + Environment.NewLine + Environment.NewLine + "And relations:" + Environment.NewLine + Environment.NewLine + string.Join(Environment.NewLine, this.relations)); }