public void Apply_should_introduce_cascade_delete_on_constraints()
        {
            var databaseMapping
                = new DbDatabaseMapping()
                    .Initialize(new EdmModel().Initialize(), new DbDatabaseMetadata().Initialize());

            var foreignKeyConstraint = new DbForeignKeyConstraintMetadata();

            Assert.Equal(DbOperationAction.None, foreignKeyConstraint.DeleteAction);

            var table = new DbTableMetadata();
            table.ForeignKeyConstraints.Add(foreignKeyConstraint);

            var associationType = new EdmAssociationType().Initialize();
            associationType.SourceEnd.EndKind = EdmAssociationEndKind.Many;
            associationType.SourceEnd.EntityType = new EdmEntityType();
            associationType.TargetEnd.EndKind = EdmAssociationEndKind.Many;
            associationType.TargetEnd.EntityType = new EdmEntityType();

            var associationSetMapping = databaseMapping.AddAssociationSetMapping(new EdmAssociationSet { ElementType = associationType });
            associationSetMapping.Table = table;

            ((IDbMappingConvention)new ManyToManyCascadeDeleteConvention()).Apply(databaseMapping);

            Assert.Equal(DbOperationAction.Cascade, foreignKeyConstraint.DeleteAction);
        }
        internal void WriteForeignKeyConstraintElement(
            DbTableMetadata dbTableMetadata, DbForeignKeyConstraintMetadata tableFKConstraint)
        {
            _xmlWriter.WriteStartElement(SsdlConstants.Element_Association);
            _xmlWriter.WriteAttributeString(SsdlConstants.Attribute_Name, tableFKConstraint.Name);

            var multiplicity = DetermineMultiplicity(dbTableMetadata, tableFKConstraint);

            // If the FK is a Self Ref, then we need to append a suffix to the second role name
            var roleNames = DbModelSsdlHelper.GetRoleNamePair(tableFKConstraint.PrincipalTable, dbTableMetadata);

            // End
            WriteAssociationEndElementHeader(roleNames[0], tableFKConstraint.PrincipalTable, multiplicity.Key);

            if (tableFKConstraint.DeleteAction
                != DbOperationAction.None)
            {
                WriteOperationActionElement(SsdlConstants.Element_OnDelete, tableFKConstraint.DeleteAction);
            }

            WriteEndElement();
            WriteAssociationEndElementHeader(roleNames[1], dbTableMetadata, multiplicity.Value);
            WriteEndElement();

            // ReferentialConstraint
            WriteReferentialConstraintElementHeader();
            WriteReferentialConstraintRoleElement(
                SsdlConstants.Element_PrincipalRole, roleNames[0], tableFKConstraint.PrincipalTable.KeyColumns);
            WriteReferentialConstraintRoleElement(
                SsdlConstants.Element_DependentRole, roleNames[1], tableFKConstraint.DependentColumns);
            WriteEndElement();

            WriteEndElement();
        }
        public void Configure_should_update_table_name_when_base_type_is_null()
        {
            var entityMappingConfiguration = new EntityMappingConfiguration
                                                 {
                                                     TableName = new DatabaseName("Foo")
                                                 };
            var entityTypeMapping = new DbEntityTypeMapping
                                        {
                                            EntityType = new EdmEntityType()
                                        };
            var table = new DbTableMetadata
                            {
                                Name = "foo"
                            };
            entityTypeMapping.TypeMappingFragments.Add(
                new DbEntityTypeMappingFragment
                    {
                        Table = table
                    });

            var databaseMapping =
                new DbDatabaseMapping().Initialize(new EdmModel().Initialize(), new DbDatabaseMetadata().Initialize());
            databaseMapping.Database.AddTable("foo");
            entityMappingConfiguration.Configure(
                databaseMapping, ProviderRegistry.Sql2008_ProviderManifest, entityTypeMapping.EntityType, ref entityTypeMapping, false, 0, 1);

            Assert.Equal("Foo", table.GetTableName().Name);
        }
 internal void WriteAssociationSetEndElement(DbTableMetadata end, string roleName)
 {
     _xmlWriter.WriteStartElement(SsdlConstants.Element_End);
     _xmlWriter.WriteAttributeString(SsdlConstants.Attribute_Role, roleName);
     _xmlWriter.WriteAttributeString(SsdlConstants.Attribute_EntitySet, end.Name);
     _xmlWriter.WriteEndElement();
 }
        public static DbTableColumnMetadata IncludeColumn(
            DbTableMetadata table, DbTableColumnMetadata templateColumn, bool useExisting)
        {
            Contract.Requires(table != null);
            Contract.Requires(templateColumn != null);

            var existingColumn =
                table.Columns.SingleOrDefault(c => string.Equals(c.Name, templateColumn.Name, StringComparison.Ordinal));

            if (existingColumn == null)
            {
                templateColumn = templateColumn.Clone();
            }
            else if (!useExisting
                     && !existingColumn.IsPrimaryKeyColumn)
            {
                templateColumn = templateColumn.Clone();
            }
            else
            {
                templateColumn = existingColumn;
            }

            return AddColumn(table, templateColumn);
        }
Пример #6
0
 public TableMapping(DbTableMetadata table)
 {
     //Contract.Requires(table != null);
     _table = table;
     _entityTypes = new SortedEntityTypeIndex();
     _columns = new List<ColumnMapping>();
 }
Пример #7
0
 /// <summary>
 ///     Return role name pair
 /// </summary>
 /// <param name="firstTable"> </param>
 /// <param name="secondTable"> </param>
 /// <returns> </returns>
 internal static string[] GetRoleNamePair(DbTableMetadata firstTable, DbTableMetadata secondTable)
 {
     return new[]
                {
                    firstTable.Name,
                    firstTable != secondTable ? secondTable.Name : secondTable.Name + selfRefRoleNameSuffix
                };
 }
 protected override void VisitKeyColumns(DbTableMetadata item, IEnumerable<DbTableColumnMetadata> keyColumns)
 {
     _schemaWriter.WriteDelaredKeyPropertiesElementHeader();
     foreach (var keyColumn in keyColumns)
     {
         _schemaWriter.WriteDelaredKeyPropertyRefElement(keyColumn);
     }
     _schemaWriter.WriteEndElement();
 }
        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 AddColumn_should_set_properties_and_add_to_columns()
        {
            var table = new DbTableMetadata();

            var tableColumn = table.AddColumn("Foo");

            Assert.NotNull(tableColumn);
            Assert.Equal("Foo", tableColumn.Name);
            Assert.True(table.Columns.Contains(tableColumn));
        }
        public void Apply_should_order_by_annotation_if_given()
        {
            var table = new DbTableMetadata();
            table.AddColumn("C").SetOrder(2);
            table.AddColumn("Id").SetOrder(1);

            ((IDbConvention<DbTableMetadata>)new ColumnOrderingConvention()).Apply(table, new DbDatabaseMetadata());

            Assert.Equal(2, table.Columns.Count);
            Assert.Equal("Id", table.Columns.First().Name);
        }
        public void Apply_should_sort_unannotated_in_given_order()
        {
            var table = new DbTableMetadata();
            table.AddColumn("C");
            table.AddColumn("Id");

            ((IDbConvention<DbTableMetadata>)new ColumnOrderingConvention()).Apply(table, new DbDatabaseMetadata());

            Assert.Equal(2, table.Columns.Count);
            Assert.Equal("C", table.Columns.First().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);
        }
        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 static DbTableColumnMetadata RemoveColumn(DbTableMetadata table, DbTableColumnMetadata column)
        {
            Contract.Requires(table != null);
            Contract.Requires(column != null);

            if (!column.IsPrimaryKeyColumn)
            {
                table.Columns.Remove(column);
            }

            return column;
        }
 internal void WriteEntitySetElementHeader(DbSchemaMetadata containingSchema, DbTableMetadata entitySet)
 {
     _xmlWriter.WriteStartElement(SsdlConstants.Element_EntitySet);
     _xmlWriter.WriteAttributeString(SsdlConstants.Attribute_Name, entitySet.Name);
     _xmlWriter.WriteAttributeString(
         SsdlConstants.Attribute_EntityType, GetQualifiedTypeName(SsdlConstants.Value_Self, entitySet.Name));
     if (containingSchema.DatabaseIdentifier != null)
     {
         _xmlWriter.WriteAttributeString(SsdlConstants.Attribute_Schema, containingSchema.DatabaseIdentifier);
     }
     if (entitySet.DatabaseIdentifier != null)
     {
         _xmlWriter.WriteAttributeString(SsdlConstants.Attribute_Table, entitySet.DatabaseIdentifier);
     }
 }
        protected override void ValidateColumns(DbTableMetadata table)
        {
            var hasDuplicates
                = table.Columns
                    .Select(c => c.GetOrder())
                    .Where(o => o != null)
                    .GroupBy(o => o)
                    .Where(g => g.Count() > 1)
                    .Any();

            if (hasDuplicates)
            {
                throw Error.DuplicateConfiguredColumnOrder(table.DatabaseIdentifier);
            }
        }
 protected virtual void VisitDbTableMetadata(DbTableMetadata item)
 {
     VisitDbSchemaMetadataItem(item);
     if (item != null)
     {
         if (item.HasColumns)
         {
             VisitKeyColumns(item, item.KeyColumns);
             VisitColumns(item, item.Columns);
         }
         if (item.HasForeignKeyConstraints)
         {
             VisitForeignKeyConstraints(item, item.ForeignKeyConstraints);
         }
     }
 }
        public static DbTableMetadata AddTable(this DbDatabaseMetadata database, string name)
        {
            //Contract.Requires(database != null);
            //Contract.Requires(!string.IsNullOrWhiteSpace(name));
            Contract.Assert(database.Schemas.Count == 1);

            var schema = database.Schemas.Single();
            var uniqueIdentifier = schema.Tables.UniquifyName(name);

            var table = new DbTableMetadata
                {
                    Name = uniqueIdentifier,
                    DatabaseIdentifier = uniqueIdentifier
                };

            schema.Tables.Add(table);

            return table;
        }
        private static DbTableColumnMetadata AddColumn(DbTableMetadata table, DbTableColumnMetadata column)
        {
            Contract.Requires(table != null);
            Contract.Requires(column != null);

            if (!table.Columns.Contains(column))
            {
                var configuration = column.GetConfiguration() as PrimitivePropertyConfiguration;

                if ((configuration == null)
                    || string.IsNullOrWhiteSpace(configuration.ColumnName))
                {
                    var preferredName = column.GetPreferredName() ?? column.Name;
                    column.SetUnpreferredUniqueName(column.Name);
                    column.Name = table.Columns.UniquifyName(preferredName);
                }

                table.Columns.Add(column);
            }

            return column;
        }
        public static DbTableColumnMetadata IncludeColumn(DbTableMetadata table, string columnName, bool useExisting)
        {
            Contract.Requires(table != null);
            Contract.Requires(columnName != null);

            var existingColumn =
                table.Columns.SingleOrDefault(c => string.Equals(c.Name, columnName, StringComparison.Ordinal));
            DbTableColumnMetadata column = null;
            if (existingColumn == null)
            {
                column = table.AddColumn(columnName);
            }
            else if (!useExisting
                     && !existingColumn.IsPrimaryKeyColumn)
            {
                column = table.AddColumn(columnName);
            }
            else
            {
                column = existingColumn;
            }

            return AddColumn(table, column);
        }
 protected override void VisitForeignKeyConstraints(
     DbTableMetadata item, IEnumerable<DbForeignKeyConstraintMetadata> foreignKeyConstraints)
 {
     _foreignKeyConstraintList.Add(item, foreignKeyConstraints);
 }
 protected override void VisitDbTableMetadata(DbTableMetadata item)
 {
     _schemaWriter.WriteEntityTypeElementHeader(item);
     base.VisitDbTableMetadata(item);
     _schemaWriter.WriteEndElement();
 }
 protected override void VisitDbTableMetadata(DbTableMetadata item)
 {
     _containerSchemaWriter.WriteEntitySetElementHeader(currentSchema, item);
     VisitForeignKeyConstraints(item, item.ForeignKeyConstraints);
     _schemaWriter.WriteEndElement();
 }
        public static void AddTypeConstraint(
            EdmEntityType entityType, DbTableMetadata principalTable, DbTableMetadata dependentTable, bool isSplitting)
        {
            Contract.Requires(principalTable != null);
            Contract.Requires(dependentTable != null);
            Contract.Requires(entityType != null);

            var foreignKeyConstraintMetadata = new DbForeignKeyConstraintMetadata
                {
                    Name =
                        String.Format(
                            CultureInfo.InvariantCulture,
                            "{0}_TypeConstraint_From_{1}_To_{2}",
                            entityType.Name,
                            principalTable.Name,
                            dependentTable.Name),
                    PrincipalTable = principalTable
                };

            if (isSplitting)
            {
                foreignKeyConstraintMetadata.SetIsSplitConstraint();
            }
            else
            {
                foreignKeyConstraintMetadata.SetIsTypeConstraint();
            }
            dependentTable.Columns
                .Where(c => c.IsPrimaryKeyColumn)
                .Each(c => foreignKeyConstraintMetadata.DependentColumns.Add(c));

            dependentTable.ForeignKeyConstraints.Add(foreignKeyConstraintMetadata);

            //If "DbStoreGeneratedPattern.Identity" was copied from the parent table, it should be removed
            dependentTable.Columns.Where(c => c.IsPrimaryKeyColumn).Each(c => c.RemoveStoreGeneratedIdentityPattern());
        }
 public static bool UsesOtherTables(this DbEntityTypeMapping entityTypeMapping, DbTableMetadata table)
 {
     return entityTypeMapping.TypeMappingFragments.Any(f => f.Table != table);
 }
 protected virtual void VisitForeignKeyConstraints(
     DbTableMetadata item, IEnumerable<DbForeignKeyConstraintMetadata> foreignKeyConstraints)
 {
     VisitCollection(foreignKeyConstraints, VisitDbForeignKeyConstraintMetadata);
 }
 protected virtual void VisitColumns(DbTableMetadata item, IEnumerable<DbTableColumnMetadata> columns)
 {
     VisitCollection(columns, VisitDbTableColumnMetadata);
 }
Пример #29
0
 private void MarkColumnsAsNonNullableIfNoTableSharing(
     EdmEntitySet entitySet, DbTableMetadata table, EdmEntityType dependentEndEntityType,
     IEnumerable<DbTableColumnMetadata> columns)
 {
     // determine if base entities share this table, if not, the foreign keys can be non-nullable
     var mappedBaseTypes =
         _tableMappings[table].EntityTypes.GetEntityTypes(entitySet).Where(
             et =>
             et != dependentEndEntityType &&
             (et.IsAncestorOf(dependentEndEntityType) || !dependentEndEntityType.IsAncestorOf(et)));
     if (mappedBaseTypes.Count() == 0
         || mappedBaseTypes.All(et => et.IsAbstract))
     {
         columns.Each(c => c.IsNullable = false);
     }
 }
Пример #30
0
 private TableMapping FindOrCreateTableMapping(DbTableMetadata table)
 {
     TableMapping tableMapping;
     if (!_tableMappings.TryGetValue(table, out tableMapping))
     {
         tableMapping = new TableMapping(table);
         _tableMappings.Add(table, tableMapping);
     }
     return tableMapping;
 }