private static bool RemapsInheritedProperties(
            DbDatabaseMapping databaseMapping, StorageEntityTypeMapping entityTypeMapping)
        {
            var inheritedProperties = entityTypeMapping.EntityType.Properties
                                                       .Except(entityTypeMapping.EntityType.DeclaredProperties)
                                                       .Except(entityTypeMapping.EntityType.GetKeyProperties());

            foreach (var property in inheritedProperties)
            {
                var fragment = GetFragmentForPropertyMapping(entityTypeMapping, property);

                if (fragment != null)
                {
                    // find if this inherited property is mapped to another table by a base type
                    var baseType = (EntityType)entityTypeMapping.EntityType.BaseType;
                    while (baseType != null)
                    {
                        if (databaseMapping.GetEntityTypeMappings(baseType)
                                           .Select(baseTypeMapping => GetFragmentForPropertyMapping(baseTypeMapping, property))
                                           .Any(
                                               baseFragment => baseFragment != null
                                                               && baseFragment.Table != fragment.Table))
                        {
                            return true;
                        }
                        baseType = (EntityType)baseType.BaseType;
                    }
                }
            }
            return false;
        }
Exemplo n.º 2
0
        public void Serialize(DbDatabaseMapping databaseMapping, XmlWriter xmlWriter)
        {
            DebugCheck.NotNull(xmlWriter);
            DebugCheck.NotNull(databaseMapping);
            Debug.Assert(databaseMapping.Model != null);
            Debug.Assert(databaseMapping.Database != null);

            _xmlWriter = xmlWriter;
            _databaseMapping = databaseMapping;
            _version = databaseMapping.Model.SchemaVersion;
            _namespace = Equals(_version, XmlConstants.EdmVersionForV3)
                             ? EdmXmlNamespaceV3
                             : (Equals(_version, XmlConstants.EdmVersionForV2) ? EdmXmlNamespaceV2 : EdmXmlNamespaceV1);

            _xmlWriter.WriteStartDocument();

            using (Element("Edmx", "Version", string.Format(CultureInfo.InvariantCulture, "{0:F1}", _version)))
            {
                WriteEdmxRuntime();
                WriteEdmxDesigner();
            }

            _xmlWriter.WriteEndDocument();
            _xmlWriter.Flush();
        }
        public void Configure_should_update_table_name_when_base_type_is_null()
        {
            var entityMappingConfiguration
                = new EntityMappingConfiguration
                      {
                          TableName = new DatabaseName("Foo")
                      };

            var entityTypeMapping = new EntityTypeMapping(null);

            entityTypeMapping.AddType(new EntityType("E", "N", DataSpace.CSpace));

            var databaseMapping =
                new DbDatabaseMapping().Initialize(new EdmModel(DataSpace.CSpace), new EdmModel(DataSpace.SSpace));

            var table = databaseMapping.Database.AddTable("foo");
            var entitySet = databaseMapping.Database.GetEntitySet(table);

            entityTypeMapping.AddFragment(new MappingFragment(entitySet, entityTypeMapping, false));
            
            entityMappingConfiguration.Configure(
                databaseMapping, databaseMapping.Model.Container.EntitySets,
                ProviderRegistry.Sql2008_ProviderManifest, entityTypeMapping.EntityType,
                ref entityTypeMapping, false, 0, 1,
                new Dictionary<string, object>());

            Assert.Equal("Foo", table.GetTableName().Name);
        }
        private static void GenerateForeignKeyAssociationType(
            AssociationType associationType, DbDatabaseMapping databaseMapping)
        {
            DebugCheck.NotNull(associationType);
            DebugCheck.NotNull(databaseMapping);
            Debug.Assert(associationType.Constraint != null);

            var dependentEnd = associationType.Constraint.DependentEnd;
            var principalEnd = associationType.GetOtherEnd(dependentEnd);
            var principalEntityTypeMapping = GetEntityTypeMappingInHierarchy(databaseMapping, principalEnd.GetEntityType());
            var dependentEntityTypeMapping = GetEntityTypeMappingInHierarchy(databaseMapping, dependentEnd.GetEntityType());

            var foreignKeyConstraint
                = new ForeignKeyBuilder(databaseMapping.Database, associationType.Name)
                    {
                        PrincipalTable =
                            principalEntityTypeMapping.MappingFragments.Single().Table,
                        DeleteAction = principalEnd.DeleteBehavior != OperationAction.None
                                           ? principalEnd.DeleteBehavior
                                           : OperationAction.None
                    };

            dependentEntityTypeMapping
                .MappingFragments
                .Single()
                .Table
                .AddForeignKey(foreignKeyConstraint);

            foreignKeyConstraint.DependentColumns = associationType.Constraint.ToProperties.Select(
                dependentProperty => dependentEntityTypeMapping.GetPropertyMapping(dependentProperty).ColumnProperty);

            foreignKeyConstraint.SetAssociationType(associationType);
        }
        public static void SyncNullabilityCSSpace(
            this ColumnMappingBuilder propertyMappingBuilder,
            DbDatabaseMapping databaseMapping,
            IEnumerable<EntitySet> entitySets,
            EntityType toTable)
        {
            DebugCheck.NotNull(propertyMappingBuilder);

            var property = propertyMappingBuilder.PropertyPath.Last();

            EntitySetMapping setMapping = null;

            var baseType = (EntityType)property.DeclaringType.BaseType;
            if (baseType != null)
            {
                setMapping = GetEntitySetMapping(databaseMapping, baseType, entitySets);
            }

            while (baseType != null)
            {
                if (toTable == setMapping.EntityTypeMappings.First(m => m.EntityType == baseType).GetPrimaryTable())
                {
                    // CodePlex 2254: If current table is part of TPH mapping below the TPT mapping we are processing, then
                    // don't change the nullability because the TPH nullability calculated previously is still correct.
                    return;
                }

                baseType = (EntityType)baseType.BaseType;
            }

            propertyMappingBuilder.ColumnProperty.Nullable = property.Nullable;
        }
Exemplo n.º 6
0
        internal void WriteSchema(DbDatabaseMapping databaseMapping)
        {
            DebugCheck.NotNull(databaseMapping);

            WriteSchemaElementHeader();
            WriteDbModelElement(databaseMapping);
            WriteEndElement();
        }
        internal void WriteSchema(DbDatabaseMapping databaseMapping)
        {
            DebugCheck.NotNull(databaseMapping);

            WriteSchemaElementHeader();
            WriteDbModelElement(databaseMapping);
            WriteEndElement();
        }
Exemplo n.º 8
0
        // <summary>
        // Initializes a new instance of the <see cref="DbModel" /> class.
        // </summary>
        internal DbModel(DbDatabaseMapping databaseMapping, DbModelBuilder modelBuilder)
        {
            DebugCheck.NotNull(databaseMapping);
            DebugCheck.NotNull(modelBuilder);

            _databaseMapping = databaseMapping;
            _cachedModelBuilder = modelBuilder;
        }
Exemplo n.º 9
0
        internal DbModel(DbProviderInfo providerInfo, DbProviderManifest providerManifest)
        {
            DebugCheck.NotNull(providerInfo);
            DebugCheck.NotNull(providerManifest);

            _databaseMapping = new DbDatabaseMapping().Initialize(
                EdmModel.CreateConceptualModel(),
                EdmModel.CreateStoreModel(providerInfo, providerManifest));
        }
Exemplo n.º 10
0
        private void WriteDbModelElement(DbDatabaseMapping databaseMapping)
        {
            DebugCheck.NotNull(databaseMapping);

            _entityTypeNamespace = databaseMapping.Model.NamespaceNames.SingleOrDefault();
            _dbSchemaName = databaseMapping.Database.Containers.Single().Name;

            WriteEntityContainerMappingElement(databaseMapping.EntityContainerMappings.First());
        }
Exemplo n.º 11
0
        private void WriteDbModelElement(DbDatabaseMapping databaseMapping)
        {
            DebugCheck.NotNull(databaseMapping);

            _entityTypeNamespace = databaseMapping.Model.NamespaceNames.SingleOrDefault();
            _dbSchemaName        = databaseMapping.Database.Containers.Single().Name;

            WriteEntityContainerMappingElement(databaseMapping.EntityContainerMappings.First());
        }
        private static DbDatabaseMapping InitializeDatabaseMapping(EdmModel model)
        {
            DebugCheck.NotNull(model);

            var databaseMapping
                = new DbDatabaseMapping()
                    .Initialize(model, new EdmModel(DataSpace.SSpace, model.SchemaVersion));

            return databaseMapping;
        }
Exemplo n.º 13
0
        // <summary>
        // Serialize the <see cref="DbModel" /> to the XmlWriter
        // </summary>
        // <param name="databaseMapping"> The DbModel to serialize </param>
        // <param name="xmlWriter"> The XmlWriter to serialize to </param>
        public virtual bool Serialize(DbDatabaseMapping databaseMapping, XmlWriter xmlWriter)
        {
            Check.NotNull(databaseMapping, "databaseMapping");
            Check.NotNull(xmlWriter, "xmlWriter");

            var schemaWriter = new MslXmlSchemaWriter(xmlWriter, databaseMapping.Model.SchemaVersion);

            schemaWriter.WriteSchema(databaseMapping);

            return(true);
        }
        public void Can_set_and_get_Model()
        {
            var mapping = new DbDatabaseMapping();
            
            Assert.Null(mapping.Model);

            var model = new EdmModel(DataSpace.CSpace);
            mapping.Model = model;

            Assert.Same(model, mapping.Model);
        }
Exemplo n.º 15
0
        /// <summary>
        ///     Serialize the <see cref="DbModel" /> to the XmlWriter
        /// </summary>
        /// <param name="databaseMapping"> The DbModel to serialize </param>
        /// <param name="xmlWriter"> The XmlWriter to serialize to </param>
        public virtual bool Serialize(DbDatabaseMapping databaseMapping, XmlWriter xmlWriter)
        {
            Check.NotNull(databaseMapping, "databaseMapping");
            Check.NotNull(xmlWriter, "xmlWriter");

            var schemaWriter = new MslXmlSchemaWriter(xmlWriter, databaseMapping.Model.SchemaVersion);

            schemaWriter.WriteSchema(databaseMapping);

            return true;
        }
        public void Can_set_and_get_Database()
        {
            var mapping = new DbDatabaseMapping();

            Assert.Null(mapping.Database);

            var storeModel = new EdmModel(DataSpace.SSpace);
            mapping.Database = storeModel;

            Assert.Same(storeModel, mapping.Database);
        }
        public void Can_add_container_mappings()
        {
            var mapping = new DbDatabaseMapping();

            Assert.Empty(mapping.EntityContainerMappings);

            var containerMapping = new EntityContainerMapping(new EntityContainer());
            mapping.AddEntityContainerMapping(containerMapping);

            Assert.Same(containerMapping, mapping.EntityContainerMappings.Single());
        }
        public void Can_set_and_get_Model()
        {
            var mapping = new DbDatabaseMapping();

            Assert.Null(mapping.Model);

            var model = new EdmModel(DataSpace.CSpace);

            mapping.Model = model;

            Assert.Same(model, mapping.Model);
        }
        public void Can_add_container_mappings()
        {
            var mapping = new DbDatabaseMapping();

            Assert.Empty(mapping.EntityContainerMappings);

            var containerMapping = new EntityContainerMapping(new EntityContainer());

            mapping.AddEntityContainerMapping(containerMapping);

            Assert.Same(containerMapping, mapping.EntityContainerMappings.Single());
        }
        public void Can_set_and_get_Database()
        {
            var mapping = new DbDatabaseMapping();

            Assert.Null(mapping.Database);

            var storeModel = new EdmModel(DataSpace.SSpace);

            mapping.Database = storeModel;

            Assert.Same(storeModel, mapping.Database);
        }
        void IDbMappingConvention.Apply(DbDatabaseMapping databaseMapping)
        {
            Check.NotNull(databaseMapping, "databaseMapping");

            databaseMapping.EntityContainerMappings
                           .SelectMany(ecm => ecm.AssociationSetMappings)
                           .Where(
                               asm => asm.AssociationSet.ElementType.IsManyToMany()
                                      && !asm.AssociationSet.ElementType.IsSelfReferencing())
                           .SelectMany(asm => asm.Table.ForeignKeyBuilders)
                           .Each(fk => fk.DeleteAction = OperationAction.Cascade);
        }
        // <summary>
        // Builds and stores the workspace based on the given code first configuration.
        // </summary>
        // <param name="databaseMapping"> The code first EDM model. </param>
        public CodeFirstCachedMetadataWorkspace(DbDatabaseMapping databaseMapping)
        {
            DebugCheck.NotNull(databaseMapping);

            _providerInfo = databaseMapping.ProviderInfo;
            _metadataWorkspace = databaseMapping.ToMetadataWorkspace();
            _assemblies = databaseMapping.Model.GetClrTypes().Select(t => t.Assembly()).Distinct().ToList();

            Debug.Assert(databaseMapping.Model.Containers.Count() == 1, "Expecting Code First to create only one container.");

            _defaultContainerName = databaseMapping.Model.Containers.First().Name;
        }
 internal static string SerializeToString(DbDatabaseMapping databaseMapping)
 {
     var edmx = new StringBuilder();
     new EdmxSerializer().Serialize(
         databaseMapping, 
         XmlWriter.Create(
             edmx, new XmlWriterSettings
                       {
                           Indent = true
                       }));
     return edmx.ToString();
 }
        private void GenerateEntityTypes(DbDatabaseMapping databaseMapping)
        {
            DebugCheck.NotNull(databaseMapping);

            foreach (var entityType in databaseMapping.Model.EntityTypes)
            {
                if (!entityType.Abstract)
                {
                    new TableMappingGenerator(_providerManifest).
                        Generate(entityType, databaseMapping);
                }
            }
        }
Exemplo n.º 25
0
        public void GetComplexParameterBindings_should_return_all_complex_parameter_bindings_for_type()
        {
            var databaseMapping
                = new DbDatabaseMapping()
                    .Initialize(
                        new EdmModel(DataSpace.CSpace),
                        new EdmModel(DataSpace.SSpace));

            var entityType = new EntityType("E", "N", DataSpace.CSpace);
            var entitySet = databaseMapping.Model.AddEntitySet("ES", entityType);
            var entitySetMapping = databaseMapping.AddEntitySetMapping(entitySet);

            var complexType1 = new ComplexType();
            complexType1.Annotations.SetClrType(typeof(string));

            var complexType2 = new ComplexType();
            complexType2.Annotations.SetClrType(typeof(object));

            var storageModificationFunctionMapping
                = new StorageModificationFunctionMapping(
                    entitySet,
                    entityType,
                    new EdmFunction("F", "N", DataSpace.SSpace),
                    new[]
                        {
                            new StorageModificationFunctionParameterBinding(
                                new FunctionParameter(),
                                new StorageModificationFunctionMemberPath(
                                new EdmMember[]
                                    {
                                        EdmProperty.Complex("C1", complexType1),
                                        EdmProperty.Complex("C2", complexType2),
                                        new EdmProperty("M")
                                    },
                                null),
                                true
                                )
                        },
                    null,
                    null);

            entitySetMapping.AddModificationFunctionMapping(
                new StorageEntityTypeModificationFunctionMapping(
                    entityType,
                    storageModificationFunctionMapping,
                    storageModificationFunctionMapping,
                    storageModificationFunctionMapping));

            Assert.Equal(3, databaseMapping.GetComplexParameterBindings(typeof(string)).Count());
            Assert.Equal(3, databaseMapping.GetComplexParameterBindings(typeof(object)).Count());
        }
Exemplo n.º 26
0
        public void UpdateEdmxFromModel_updates_csdl_ssdl_msl()
        {
            var inputXml = XDocument.Parse("<root />");
            var databaseMapping =
                new DbDatabaseMapping
                    {
                        Model = new EdmModel(DataSpace.CSpace),
                        Database = new EdmModel(DataSpace.SSpace)
                    };
            var model = new DbModel(databaseMapping, new DbModelBuilder());

            var mockEdmxHelper = new Mock<EdmxHelper>(inputXml);
            mockEdmxHelper.Setup(
                h => h.UpdateStorageModels(
                    It.Is<EdmModel>(m => m == databaseMapping.Database),
                    It.Is<string>(n => n == "storeNamespace"),
                    It.Is<DbProviderInfo>(i => i == model.ProviderInfo),
                    It.IsAny<List<EdmSchemaError>>()))
                .Returns(true);
            mockEdmxHelper.Setup(
                h => h.UpdateConceptualModels(
                    It.Is<EdmModel>(m => m == databaseMapping.Model),
                    It.Is<string>(n => n == "entityModelNamespace")))
                .Returns(true);
            mockEdmxHelper.Setup(
                h => h.UpdateMapping(
                    It.Is<DbModel>(m => m == model)))
                .Returns(true);
            mockEdmxHelper.Object.UpdateEdmxFromModel(
                model, "storeNamespace", "entityModelNamespace", new List<EdmSchemaError>());

            mockEdmxHelper
                .Verify(
                    h => h.UpdateStorageModels(
                        It.Is<EdmModel>(m => m == databaseMapping.Database),
                        It.Is<string>(n => n == "storeNamespace"),
                        It.Is<DbProviderInfo>(i => i == model.ProviderInfo),
                        It.IsAny<List<EdmSchemaError>>()), Times.Once());

            mockEdmxHelper
                .Verify(
                    h => h.UpdateConceptualModels(
                        It.Is<EdmModel>(m => m == databaseMapping.Model),
                        It.Is<string>(n => n == "entityModelNamespace")), Times.Once());

            mockEdmxHelper
                .Verify(
                    h => h.UpdateMapping(
                        It.Is<DbModel>(m => m == model)), Times.Once());
        }
        public static DbModel Build(SimpleMappingContext mappingContext)
        {
            Debug.Assert(mappingContext != null, "mappingContext != null");

            var databaseMapping =
                new DbDatabaseMapping
                    {
                        Database = mappingContext.StoreModel,
                        Model = BuildEntityModel(mappingContext)
                    };

            databaseMapping.AddEntityContainerMapping(BuildEntityContainerMapping(mappingContext));

            return new DbModel(databaseMapping, new DbModelBuilder());
        }
        private static void GenerateEntityTypes(DbDatabaseMapping databaseMapping)
        {
            DebugCheck.NotNull(databaseMapping);

            foreach (var entityType in databaseMapping.Model.EntityTypes)
            {
                if (entityType.Abstract
                    && databaseMapping.Model.EntityTypes.All(e => e.BaseType != entityType))
                {
                    throw new InvalidOperationException(Strings.UnmappedAbstractType(entityType.GetClrType()));
                }

                new TableMappingGenerator(databaseMapping.ProviderManifest).
                    Generate(entityType, databaseMapping);
            }
        }
        private static void GenerateDiscriminators(DbDatabaseMapping databaseMapping)
        {
            DebugCheck.NotNull(databaseMapping);

            foreach (var entitySetMapping in databaseMapping.GetEntitySetMappings())
            {
                if (entitySetMapping.EntityTypeMappings.Count() <= 1)
                {
                    continue;
                }

                var typeUsage
                    = databaseMapping.ProviderManifest.GetStoreType(DiscriminatorTypeUsage);

                var discriminatorColumn
                    = new EdmProperty(DiscriminatorColumnName, typeUsage)
                        {
                            Nullable = false,
                            DefaultValue = "(Undefined)"
                        };

                entitySetMapping
                    .EntityTypeMappings
                    .First()
                    .MappingFragments
                    .Single()
                    .Table
                    .AddColumn(discriminatorColumn);

                foreach (var entityTypeMapping in entitySetMapping.EntityTypeMappings)
                {
                    // Abstract classes don't need a discriminator as they won't be directly materialized
                    if (entityTypeMapping.EntityType.Abstract)
                    {
                        continue;
                    }

                    var entityTypeMappingFragment = entityTypeMapping.MappingFragments.Single();

                    entityTypeMappingFragment.SetDefaultDiscriminator(discriminatorColumn);

                    entityTypeMappingFragment
                        .AddDiscriminatorCondition(discriminatorColumn, entityTypeMapping.EntityType.Name);
                }
            }
        }
        private static EntitySetMapping GetEntitySetMapping(
            DbDatabaseMapping databaseMapping,
            EntityType cSpaceEntityType,
            IEnumerable<EntitySet> entitySets)
        {
            while (cSpaceEntityType.BaseType != null)
            {
                cSpaceEntityType = (EntityType)cSpaceEntityType.BaseType;
            }

            var cSpaceEntitySet = entitySets.First(s => s.ElementType == cSpaceEntityType);
            
            return databaseMapping
                .EntityContainerMappings
                .First()
                .EntitySetMappings
                .First(m => m.EntitySet == cSpaceEntitySet);
        }
        public void Generate(AssociationType associationType, DbDatabaseMapping databaseMapping)
        {
            DebugCheck.NotNull(associationType);
            DebugCheck.NotNull(databaseMapping);

            if (associationType.Constraint != null)
            {
                GenerateForeignKeyAssociationType(associationType, databaseMapping);
            }
            else if (associationType.IsManyToMany())
            {
                GenerateManyToManyAssociation(associationType, databaseMapping);
            }
            else
            {
                GenerateIndependentAssociationType(associationType, databaseMapping);
            }
        }
        public void Apply(DbDatabaseMapping databaseMapping)
        {
            Check.NotNull(databaseMapping, "databaseMapping");

            databaseMapping.EntityContainerMappings
                           .SelectMany(ecm => ecm.EntitySetMappings)
                           .Each(
                               esm =>
                                   {
                                       foreach (var etm in esm.EntityTypeMappings)
                                       {
                                           if (RemapsInheritedProperties(databaseMapping, etm)
                                               && HasBaseWithIsTypeOf(esm, etm.EntityType))
                                           {
                                               throw Error.UnsupportedHybridInheritanceMapping(etm.EntityType.Name);
                                           }
                                       }
                                   });
        }
        internal void Configure(
            DbDatabaseMapping databaseMapping, MappingFragment fragment, EntityType entityType)
        {
            DebugCheck.NotNull(fragment);

            var edmPropertyPath = EntityMappingConfiguration.PropertyPathToEdmPropertyPath(PropertyPath, entityType);

            if (edmPropertyPath.Count() > 1)
            {
                throw Error.InvalidNotNullCondition(PropertyPath.ToString(), entityType.Name);
            }

            var column
                = fragment.ColumnMappings
                          .Where(pm => pm.PropertyPath.SequenceEqual(edmPropertyPath.Single()))
                          .Select(pm => pm.ColumnProperty)
                          .SingleOrDefault();

            if (column == null
                || !fragment.Table.Properties.Contains(column))
            {
                throw Error.InvalidNotNullCondition(PropertyPath.ToString(), entityType.Name);
            }

            if (ValueConditionConfiguration.AnyBaseTypeToTableWithoutColumnCondition(
                databaseMapping, entityType, fragment.Table, column))
            {
                column.Nullable = true;
            }

            // Make the property required
            var newConfiguration = new Properties.Primitive.PrimitivePropertyConfiguration
                {
                    IsNullable = false,
                    OverridableConfigurationParts =
                        OverridableConfigurationParts.OverridableInSSpace
                };

            newConfiguration.Configure(edmPropertyPath.Single().Last());

            fragment.AddNullabilityCondition(column, isNull: false);
        }
        public void Generate(EntityType entityType, DbDatabaseMapping databaseMapping)
        {
            DebugCheck.NotNull(entityType);
            DebugCheck.NotNull(databaseMapping);

            var entitySet = databaseMapping.Model.GetEntitySet(entityType);

            var entitySetMapping
                = databaseMapping.GetEntitySetMapping(entitySet)
                  ?? databaseMapping.AddEntitySetMapping(entitySet);

            var entityTypeMapping =
                entitySetMapping.EntityTypeMappings.FirstOrDefault(
                    m => m.EntityTypes.Contains(entitySet.ElementType))
                ?? entitySetMapping.EntityTypeMappings.FirstOrDefault();

            var table
                = entityTypeMapping != null
                      ? entityTypeMapping.MappingFragments.First().Table
                      : databaseMapping.Database.AddTable(entityType.GetRootType().Name);

            entityTypeMapping = new EntityTypeMapping(null);

            var entityTypeMappingFragment
                = new MappingFragment(databaseMapping.Database.GetEntitySet(table), entityTypeMapping, false);

            entityTypeMapping.AddType(entityType);
            entityTypeMapping.AddFragment(entityTypeMappingFragment);
            entityTypeMapping.SetClrType(entityType.GetClrType());

            entitySetMapping.AddTypeMapping(entityTypeMapping);

            new PropertyMappingGenerator(_providerManifest)
                .Generate(
                    entityType,
                    entityType.Properties,
                    entitySetMapping,
                    entityTypeMappingFragment,
                    new List<EdmProperty>(),
                    false);
        }
Exemplo n.º 35
0
        public void GetComplexPropertyMappings_should_return_all_complex_property_mappings_for_type()
        {
            var databaseMapping = new DbDatabaseMapping()
                .Initialize(new EdmModel(DataSpace.CSpace), new EdmModel(DataSpace.SSpace));
            var entitySet = new EntitySet
                                {
                                    Name = "ES"
                                };
            var entitySetMapping = databaseMapping.AddEntitySetMapping(entitySet);
            var entityTypeMapping = new StorageEntityTypeMapping(null);
            entitySetMapping.AddTypeMapping(entityTypeMapping);
            var entityTypeMappingFragment = new StorageMappingFragment(entitySet, entityTypeMapping, false);
            entityTypeMapping.AddFragment(entityTypeMappingFragment);
            var complexType = new ComplexType("C");
            var propertyMapping1
                = new ColumnMappingBuilder(
                    new EdmProperty("C"),
                    new[]
                        {
                            EdmProperty.Complex("P1", complexType),
                            EdmProperty.Primitive("P", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String))
                        });
            var type = typeof(object);

            complexType.Annotations.SetClrType(type);

            entityTypeMappingFragment.AddColumnMapping(propertyMapping1);

            var propertyMapping2
                = new ColumnMappingBuilder(
                    new EdmProperty("C"),
                    new List<EdmProperty>
                        {
                            EdmProperty.Complex("P3", complexType),
                            EdmProperty.Primitive(
                                "P2", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String)),
                        });
            entityTypeMappingFragment.AddColumnMapping(propertyMapping2);

            Assert.Equal(2, databaseMapping.GetComplexPropertyMappings(typeof(object)).Count());
        }
        private void GenerateDiscriminators(DbDatabaseMapping databaseMapping)
        {
            DebugCheck.NotNull(databaseMapping);

            foreach (var entitySetMapping in databaseMapping.GetEntitySetMappings())
            {
                if (entitySetMapping.EntityTypeMappings.Count() <= 1)
                {
                    continue;
                }

                var typeUsage
                    = _providerManifest.GetStoreType(DiscriminatorTypeUsage);

                var discriminatorColumn
                    = new EdmProperty(DiscriminatorColumnName, typeUsage)
                        {
                            Nullable = false
                        };

                entitySetMapping
                    .EntityTypeMappings
                    .First()
                    .MappingFragments
                    .Single()
                    .Table
                    .AddColumn(discriminatorColumn);

                foreach (var entityTypeMapping in entitySetMapping.EntityTypeMappings)
                {
                    var entityTypeMappingFragment = entityTypeMapping.MappingFragments.Single();

                    entityTypeMappingFragment.SetDefaultDiscriminator(discriminatorColumn);

                    entityTypeMappingFragment
                        .AddDiscriminatorCondition(discriminatorColumn, entityTypeMapping.EntityType.Name);
                }
            }
        }
 internal void WriteSchema(DbDatabaseMapping databaseMapping)
 {
     this.WriteSchemaElementHeader();
     this.WriteDbModelElement(databaseMapping);
     this.WriteEndElement();
 }
 private void WriteDbModelElement(DbDatabaseMapping databaseMapping)
 {
     this._entityTypeNamespace = databaseMapping.Model.NamespaceNames.SingleOrDefault <string>();
     this._dbSchemaName        = databaseMapping.Database.Containers.Single <EntityContainer>().Name;
     this.WriteEntityContainerMappingElement(databaseMapping.EntityContainerMappings.First <EntityContainerMapping>());
 }