示例#1
0
        private void ExecuteOperations(
            string migrationId, XDocument targetModel, IEnumerable <MigrationOperation> operations, bool downgrading, bool auto = false)
        {
            DebugCheck.NotEmpty(migrationId);
            DebugCheck.NotNull(targetModel);
            DebugCheck.NotNull(operations);

            FillInForeignKeyOperations(operations, targetModel);

            var newTableForeignKeys
                = (from ct in operations.OfType <CreateTableOperation>()
                   from afk in operations.OfType <AddForeignKeyOperation>()
                   where ct.Name.EqualsIgnoreCase(afk.DependentTable)
                   select afk)
                  .ToList();

            var orderedOperations
                = operations
                  .Except(newTableForeignKeys)
                  .Concat(newTableForeignKeys)
                  .ToList();

            var createHistoryOperation
                = operations
                  .OfType <CreateTableOperation>()
                  .SingleOrDefault(o => o.IsSystem);

            if (createHistoryOperation != null)
            {
                _historyRepository.CurrentSchema
                    = createHistoryOperation.Name.ToDatabaseName().Schema;
            }

            var moveHistoryOperation
                = operations
                  .OfType <MoveTableOperation>()
                  .SingleOrDefault(o => o.IsSystem);

            if (moveHistoryOperation != null)
            {
                _historyRepository.CurrentSchema = moveHistoryOperation.NewSchema;

                moveHistoryOperation.ContextKey = _configuration.ContextKey;
            }

            if (!downgrading)
            {
                orderedOperations.Add(_historyRepository.CreateInsertOperation(migrationId, targetModel));
            }
            else if (!operations.Any(o => o.IsSystem && o is DropTableOperation))
            {
                orderedOperations.Add(_historyRepository.CreateDeleteOperation(migrationId));
            }

            var migrationStatements = SqlGenerator.Generate(orderedOperations, _providerManifestToken);

            if (auto)
            {
                // Filter duplicates when auto-migrating. Duplicates can be caused by
                // duplicates in the model such as shared FKs.

                migrationStatements
                    = migrationStatements.Distinct((m1, m2) => string.Equals(m1.Sql, m2.Sql, StringComparison.Ordinal));
            }

            base.ExecuteStatements(migrationStatements);

            if (operations.Any(o => o.IsSystem))
            {
                _historyRepository.ResetExists();
            }
        }