/// <summary> /// Searches for <see cref="System.Data.Entity.Migrations.Model.AddForeignKeyOperation"/>s in <paramref name="operations"/> and /// completes the operation by adding the principal column of the referenced table. /// </summary> /// <param name="operations">The <see cref="System.Data.Entity.Migrations.Model.MigrationOperation"/>s that possibly contain an <see cref="System.Data.Entity.Migrations.Model.AddForeignKeyOperation"/>.</param> /// <param name="sqlConnection">A connection to a SQL server where the database used in the migration is stored.</param> private void CompleteForeignKeyOperations(IEnumerable <MigrationOperation> operations, SqlConnection sqlConnection) { DebugCheck.NotNull(operations); Check.NotNull(sqlConnection, nameof(sqlConnection)); foreach ( AddForeignKeyOperation operation in operations.OfType <AddForeignKeyOperation>() .Where ( addForeignKeyOperation => ( (addForeignKeyOperation.PrincipalTable != null) && (!addForeignKeyOperation.PrincipalColumns.Any()) ) ) ) { // Go to the principal table this operation references RockContext context = new RockContext(sqlConnection.ConnectionString); XDocument targetModel = context.GetModel(); string principalTableName = GetStandardizedTableName(operation.PrincipalTable); string databaseTableName = ( from databases in targetModel.Descendants(EdmXNames.Ssdl.EntitySetNames) where new DatabaseName((string)databases.Attribute("Table"), (string)databases.Attribute("Schema")).ToString() .EqualsIgnoreCase(principalTableName) select(string) databases.Attribute("Name") ).SingleOrDefault(); if (databaseTableName != null) { // The table already exists in the database. // Enumerate all of the PrincipalColumns and add them to the operation. var databaseTable = targetModel.Descendants(EdmXNames.Ssdl.EntityTypeNames) .Single(database => ( (string)database.Attribute("Name")) .EqualsIgnoreCase(databaseTableName) ) ; databaseTable.Descendants(EdmXNames.Ssdl.PropertyRefNames).Each(column => operation.PrincipalColumns.Add((string)column.Attribute("Name"))); } else { // The table does not exist in the database. // Try to find the table in the migration operations. CreateTableOperation table = operations.OfType <CreateTableOperation>() .SingleOrDefault(createTableOperation => createTableOperation.Name.EqualsIgnoreCase(principalTableName)) ; if ((table != null) && (table.PrimaryKey != null)) { // Enumerate all of the PrincipalColumns and add them to the operation table.PrimaryKey.Columns.Each(column => operation.PrincipalColumns.Add(column)); } else { // The table does not exist in the database or in the migrations throw new Exception(string.Format("Table {0} does not exist in database {1} or in the current migration operation.", principalTableName, sqlConnection.Database)); } } } }