public void Configure_should_split_key_constraint_when_to_table_configuration()
        {
            var database = new DbDatabaseMetadata().Initialize();
            var sourceTable = database.AddTable("Source");
            var fkColumn = sourceTable.AddColumn("Fk");
            var foreignKeyConstraint = new DbForeignKeyConstraintMetadata();
            foreignKeyConstraint.DependentColumns.Add(fkColumn);
            sourceTable.ForeignKeyConstraints.Add(foreignKeyConstraint);
            var targetTable = database.AddTable("Split");
            var associationSetMapping = new DbAssociationSetMapping().Initialize();
            associationSetMapping.Table = sourceTable;
            associationSetMapping.SourceEndMapping.PropertyMappings.Add(new DbEdmPropertyMapping { Column = fkColumn });

            var independentAssociationMappingConfiguration
                = new ForeignKeyAssociationMappingConfiguration();

            independentAssociationMappingConfiguration.ToTable("Split");

            independentAssociationMappingConfiguration.Configure(associationSetMapping, database);

            Assert.True(targetTable.Columns.Contains(fkColumn));
            Assert.True(targetTable.ForeignKeyConstraints.Contains(foreignKeyConstraint));
            Assert.False(sourceTable.Columns.Contains(fkColumn));
            Assert.False(sourceTable.ForeignKeyConstraints.Contains(foreignKeyConstraint));
            Assert.Same(targetTable, associationSetMapping.Table);
        }
        public void AddTable_should_create_and_add_table_to_default_schema()
        {
            var database = new DbDatabaseMetadata().Initialize();
            var table = database.AddTable("T");

            Assert.True(database.Schemas.First().Tables.Contains(table));
            Assert.Equal("T", database.Schemas.First().Tables.First().Name);
        }
        public void Can_get_and_set_provider_annotation()
        {
            var database = new DbDatabaseMetadata().Initialize();
            var providerInfo = new DbProviderInfo("Foo", "Bar");

            database.SetProviderInfo(providerInfo);

            Assert.Same(providerInfo, database.GetProviderInfo());
        }
        public void Apply_should_ignore_current_table()
        {
            var database = new DbDatabaseMetadata().Initialize();
            var table = new DbTableMetadata { DatabaseIdentifier = "Customers" };
            database.Schemas.Single().Tables.Add(table);

            ((IDbConvention<DbTableMetadata>)new PluralizingTableNameConvention()).Apply(table, database);

            Assert.Equal("Customers", table.DatabaseIdentifier);
        }
        public void ApplyDatabase_should_run_database_conventions()
        {
            var database = new DbDatabaseMetadata().Initialize();
            var mockConvention = new Mock<IDbConvention>();
            var conventionsConfiguration = new ConventionsConfiguration(new[] { mockConvention.Object });

            conventionsConfiguration.ApplyDatabase(database);

            mockConvention.Verify(c => c.Apply(database), Times.AtMostOnce());
        }
 protected virtual void VisitDbDatabaseMetadata(DbDatabaseMetadata item)
 {
     VisitDbAliasedMetadataItem(item);
     if (item != null)
     {
         if (item.HasSchemas)
         {
             VisitCollection(item.Schemas, VisitDbSchemaMetadata);
         }
     }
 }
        public void Configure_should_throw_when_incorrect_number_of_columns_configured()
        {
            var database = new DbDatabaseMetadata().Initialize();
            var associationSetMapping = new DbAssociationSetMapping().Initialize();

            var manyToManyAssociationMappingConfiguration
                = new ManyToManyAssociationMappingConfiguration();

            manyToManyAssociationMappingConfiguration.MapLeftKey("Id1", "Id2");

            Assert.Equal(Strings.IncorrectColumnCount("Id1, Id2"), Assert.Throws<InvalidOperationException>(() => manyToManyAssociationMappingConfiguration.Configure(associationSetMapping, database)).Message);
        }
        public void Configure_should_throw_when_configured_table_not_found()
        {
            var independentAssociationMappingConfiguration
                = new ForeignKeyAssociationMappingConfiguration();

            independentAssociationMappingConfiguration.ToTable("Split");

            var associationSetMapping = new DbAssociationSetMapping().Initialize();
            var database = new DbDatabaseMetadata().Initialize();

            Assert.Equal(Strings.TableNotFound("Split"), Assert.Throws<InvalidOperationException>(() => independentAssociationMappingConfiguration.Configure(associationSetMapping, database)).Message);
        }
        public void Apply_should_ignored_configured_tables()
        {
            var database = new DbDatabaseMetadata().Initialize();
            var table = new DbTableMetadata { DatabaseIdentifier = "Customer" };
            table.SetTableName(new DatabaseName("Foo"));
            database.Schemas.Single().Tables.Add(table);

            ((IDbConvention<DbTableMetadata>)new PluralizingTableNameConvention()).Apply(table, database);

            Assert.Equal("Customer", table.DatabaseIdentifier);
            Assert.Equal("Foo", table.GetTableName().Name);
        }
        public void Apply_should_uniquify_names()
        {
            var database = new DbDatabaseMetadata().Initialize();
            var tableA = new DbTableMetadata { DatabaseIdentifier = "Customers" };
            var tableB = new DbTableMetadata { DatabaseIdentifier = "Customer" };
            database.Schemas.Single().Tables.Add(tableA);
            database.Schemas.Single().Tables.Add(tableB);

            ((IDbConvention<DbTableMetadata>)new PluralizingTableNameConvention()).Apply(tableB, database);

            Assert.Equal("Customers1", tableB.DatabaseIdentifier);
        }
        /// <summary>
        ///     Serialize the <see cref = "DbDatabaseMetadata" /> to the <see cref = "XmlWriter" />
        /// </summary>
        /// <param name = "dbDatabase"> The DbDatabaseMetadata to serialize </param>
        /// <param name = "provider"> Provider information on the Schema element </param>
        /// <param name = "providerManifestToken"> ProviderManifestToken information on the Schema element </param>
        /// <param name = "xmlWriter"> The XmlWriter to serialize to </param>
        /// <returns> </returns>
        public virtual bool Serialize(
            DbDatabaseMetadata dbDatabase, string provider, string providerManifestToken, XmlWriter xmlWriter)
        {
            //Contract.Requires(dbDatabase != null);
            //Contract.Requires(xmlWriter != null);

            // validate the model first
            // TODO: Add the validation code once the DbSchema Validator is done.

            var visitor = new DbModelSsdlSerializationVisitor(xmlWriter, dbDatabase.Version);

            visitor.Visit(dbDatabase, provider, providerManifestToken);

            return true;
        }
        public void Configure_should_rename_columns_when_right_keys_configured()
        {
            var database = new DbDatabaseMetadata().Initialize();
            var associationSetMapping = new DbAssociationSetMapping().Initialize();
            var column = new DbTableColumnMetadata();
            associationSetMapping.TargetEndMapping.PropertyMappings.Add(new DbEdmPropertyMapping { Column = column });

            var manyToManyAssociationMappingConfiguration
                = new ManyToManyAssociationMappingConfiguration();

            manyToManyAssociationMappingConfiguration.MapRightKey("NewName");

            manyToManyAssociationMappingConfiguration.Configure(associationSetMapping, database);

            Assert.Equal("NewName", column.Name);
        }
        public void Configure_should_rename_table_when_table_configured()
        {
            var database = new DbDatabaseMetadata().Initialize();
            var table = database.AddTable("OriginalName");
            var associationSetMapping = new DbAssociationSetMapping().Initialize();
            associationSetMapping.Table = table;

            var manyToManyAssociationMappingConfiguration
                = new ManyToManyAssociationMappingConfiguration();

            manyToManyAssociationMappingConfiguration.ToTable("NewName");

            manyToManyAssociationMappingConfiguration.Configure(associationSetMapping, database);

            Assert.Equal("NewName", table.GetTableName().Name);
            Assert.Same(manyToManyAssociationMappingConfiguration, table.GetConfiguration());
        }
        internal void Visit(DbDatabaseMetadata dbDatabase, string provider, string providerManifestToken)
        {
            var namespaceName = dbDatabase.Name;

            _schemaWriter.WriteSchemaElementHeader(namespaceName, provider, providerManifestToken);

            foreach (var schema in dbDatabase.Schemas)
            {
                VisitDbSchemaMetadata(schema);
            }

            // Serialize EntityContainer
            var containerVisitor = new DbModelEntityContainerSerializationVisitor(_xmlWriter, _dbVersion);

            containerVisitor.Visit(dbDatabase);

            _schemaWriter.WriteEndElement();
        }
        internal static DbDatabaseMapping Initialize(
            this DbDatabaseMapping databaseMapping, EdmModel model, DbDatabaseMetadata database)
        {
            Contract.Requires(databaseMapping != null);
            Contract.Requires(databaseMapping != null);
            Contract.Requires(database != null);

            databaseMapping.Model = model;
            databaseMapping.Database = database;
            var entityContainerMapping
                = new DbEntityContainerMapping
                    {
                        EntityContainer = model.Containers.Single()
                    };
            databaseMapping.EntityContainerMappings.Add(entityContainerMapping);

            return databaseMapping;
        }
        public static void CopyAllForeignKeyConstraintsForColumn(
            DbDatabaseMetadata database, DbTableMetadata fromTable, DbTableMetadata toTable,
            DbTableColumnMetadata column)
        {
            Contract.Requires(fromTable != null);
            Contract.Requires(toTable != null);
            Contract.Requires(column != null);

            FindAllForeignKeyConstraintsForColumn(fromTable, toTable, column)
                .ToArray()
                .Each(fk => CopyForeignKeyConstraint(database, toTable, fk));
        }
            internal void Visit(DbDatabaseMetadata dbDatabase)
            {
                _containerSchemaWriter.WriteEntityContainerElementHeader(dbDatabase.Name);

                foreach (var dbSchema in dbDatabase.Schemas)
                {
                    currentSchema = dbSchema;
                    base.VisitDbSchemaMetadata(dbSchema);
                    currentSchema = null;
                }

                _containerSchemaWriter.WriteEndElement();
            }
        public static DbTableColumnMetadata CopyColumnAndAnyConstraints(
            DbDatabaseMetadata database,
            DbTableMetadata fromTable,
            DbTableMetadata toTable,
            DbTableColumnMetadata column,
            bool useExisting,
            bool allowPkConstraintCopy)
        {
            Contract.Requires(fromTable != null);
            Contract.Requires(toTable != null);
            Contract.Requires(column != null);

            var movedColumn = column;

            if (fromTable != toTable)
            {
                movedColumn = TablePrimitiveOperations.IncludeColumn(toTable, column, useExisting);
                if (allowPkConstraintCopy || !movedColumn.IsPrimaryKeyColumn)
                {
                    ForeignKeyPrimitiveOperations.CopyAllForeignKeyConstraintsForColumn(
                        database, fromTable, toTable, column);
                }
            }

            return movedColumn;
        }
 private static void UpdatePropertyMapping(
     DbDatabaseMetadata database,
     DbEdmPropertyMapping propertyMapping,
     DbTableMetadata fromTable,
     DbTableMetadata toTable,
     bool useExisting)
 {
     propertyMapping.Column
         = TableOperations.CopyColumnAndAnyConstraints(
             database, fromTable, toTable, propertyMapping.Column, useExisting, false);
     propertyMapping.SyncNullabilityCSSpace();
 }
 void IDbConvention.Apply(DbDatabaseMetadata database)
 {
     Contract.Requires(database != null);
 }
 public static void UpdatePropertyMappings(
     DbDatabaseMetadata database,
     DbTableMetadata fromTable,
     DbEntityTypeMappingFragment fragment,
     bool useExisting)
 {
     // move the column from the formTable to the table in fragment
     if (fromTable != fragment.Table)
     {
         fragment.PropertyMappings.Each(
             pm => UpdatePropertyMapping(database, pm, fromTable, fragment.Table, useExisting));
     }
 }
        public static void MovePropertyMapping(
            DbDatabaseMetadata database,
            DbEntityTypeMappingFragment fromFragment,
            DbEntityTypeMappingFragment toFragment,
            DbEdmPropertyMapping propertyMapping,
            bool requiresUpdate,
            bool useExisting)
        {
            // move the column from the formTable to the table in fragment
            if (requiresUpdate && fromFragment.Table != toFragment.Table)
            {
                UpdatePropertyMapping(database, propertyMapping, fromFragment.Table, toFragment.Table, useExisting);
            }

            // move the propertyMapping
            fromFragment.PropertyMappings.Remove(propertyMapping);
            toFragment.PropertyMappings.Add(propertyMapping);
        }
 public static void UpdateConditions(
     DbDatabaseMetadata database, DbTableMetadata fromTable, DbEntityTypeMappingFragment fragment)
 {
     // move the condition's column from the formTable to the table in fragment
     if (fromTable != fragment.Table)
     {
         fragment.ColumnConditions.Each(
             cc =>
                 {
                     cc.Column = TableOperations.CopyColumnAndAnyConstraints(
                         database, fromTable, fragment.Table, cc.Column, true, false);
                 });
     }
 }
 internal abstract void Configure(DbAssociationSetMapping associationSetMapping, DbDatabaseMetadata database);
        public void Initialize_should_create_default_schema()
        {
            var database = new DbDatabaseMetadata().Initialize();

            Assert.Equal(3.0, database.Version);
        }
 internal override void Configure(DbAssociationSetMapping associationSetMapping, DbDatabaseMetadata database)
 {
     Contract.Requires(associationSetMapping != null);
     Contract.Requires(database != null);
 }
        public void ApplyDatabase_should_run_targeted_model_conventions()
        {
            var database = new DbDatabaseMetadata().Initialize();
            var table = database.AddTable("T");
            var mockConvention = new Mock<IDbConvention<DbTableMetadata>>();
            var conventionsConfiguration = new ConventionsConfiguration(
                new IConvention[]
                    {
                        mockConvention.Object
                    });

            conventionsConfiguration.ApplyDatabase(database);

            mockConvention.Verify(c => c.Apply(table, database), Times.AtMostOnce());
        }
        internal override void Configure(DbAssociationSetMapping associationSetMapping, DbDatabaseMetadata database)
        {
            // By convention source end contains the dependent column mappings
            var propertyMappings = associationSetMapping.SourceEndMapping.PropertyMappings;

            if (_tableName != null)
            {
                var targetTable
                    = ((from t in database.Schemas.Single().Tables
                        let n = t.GetTableName()
                        where (n != null && n.Equals(_tableName))
                        select t)
                          .SingleOrDefault())
                      ?? database.Schemas.Single().Tables
                             .SingleOrDefault(
                                 t => string.Equals(t.DatabaseIdentifier, _tableName.Name, StringComparison.Ordinal));

                if (targetTable == null)
                {
                    throw Error.TableNotFound(_tableName);
                }

                var sourceTable = associationSetMapping.Table;

                if (sourceTable != targetTable)
                {
                    var foreignKeyConstraint
                        = sourceTable.ForeignKeyConstraints
                            .Single(fk => fk.DependentColumns.SequenceEqual(propertyMappings.Select(pm => pm.Column)));

                    sourceTable.ForeignKeyConstraints.Remove(foreignKeyConstraint);
                    targetTable.ForeignKeyConstraints.Add(foreignKeyConstraint);

                    foreignKeyConstraint.DependentColumns
                        .Each(
                            c =>
                                {
                                    sourceTable.Columns.Remove(c);
                                    targetTable.Columns.Add(c);
                                });

                    associationSetMapping.Table = targetTable;
                }
            }

            if ((_keyColumnNames.Count > 0)
                && (_keyColumnNames.Count != propertyMappings.Count))
            {
                throw Error.IncorrectColumnCount(string.Join(", ", _keyColumnNames));
            }

            _keyColumnNames.Each((n, i) => propertyMappings[i].Column.Name = n);
        }
        public static void CopyAllForeignKeyConstraintsForPrimaryKeyColumns(
            DbDatabaseMetadata database, DbTableMetadata fromTable, DbTableMetadata toTable)
        {
            Contract.Requires(fromTable != null);
            Contract.Requires(toTable != null);

            foreach (var column in fromTable.KeyColumns)
            {
                FindAllForeignKeyConstraintsForColumn(fromTable, toTable, column)
                    .ToArray()
                    .Each(
                        fk =>
                            {
                                if (!fk.GetIsTypeConstraint())
                                {
                                    CopyForeignKeyConstraint(database, toTable, fk);
                                }
                            });
            }
        }
        internal override void Configure(DbAssociationSetMapping associationSetMapping, DbDatabaseMetadata database)
        {
            var table = associationSetMapping.Table;

            if (_tableName != null)
            {
                table.SetTableName(_tableName);
                table.SetConfiguration(this);
            }

            ConfigureColumnNames(_leftKeyColumnNames, associationSetMapping.SourceEndMapping.PropertyMappings);
            ConfigureColumnNames(_rightKeyColumnNames, associationSetMapping.TargetEndMapping.PropertyMappings);
        }