private static EntityType FindTableForExtraPropertyMapping(
            DbDatabaseMapping databaseMapping,
            EntityType entityType,
            EntityType fromTable,
            EntityType toTable,
            ref EntityType unmappedTable,
            ColumnMappingBuilder pm)
        {
            var extraTable = FindBaseTableForExtraPropertyMapping(databaseMapping, entityType, pm);

            if (extraTable == null)
            {
                if (fromTable != toTable &&
                    entityType.BaseType == null)
                {
                    return(fromTable);
                }

                if (unmappedTable == null)
                {
                    unmappedTable = databaseMapping.Database.AddTable(fromTable.Name, fromTable);
                }
                extraTable = unmappedTable;
            }

            return(extraTable);
        }
        private bool DiscoverIsSharingWithBase(
            DbDatabaseMapping databaseMapping, EntityType entityType, EntityType toTable)
        {
            var isSharingTableWithBase = false;

            if (entityType.BaseType != null)
            {
                var baseType        = entityType.BaseType;
                var anyBaseMappings = false;

                while (baseType != null &&
                       !isSharingTableWithBase)
                {
                    var baseMappings = databaseMapping.GetEntityTypeMappings((EntityType)baseType);

                    if (baseMappings.Any())
                    {
                        isSharingTableWithBase =
                            baseMappings.SelectMany(m => m.MappingFragments).Any(tmf => tmf.Table == toTable);
                        anyBaseMappings = true;
                    }

                    baseType = baseType.BaseType;
                }

                if (!anyBaseMappings)
                {
                    isSharingTableWithBase = TableName == null || string.IsNullOrWhiteSpace(TableName.Name);
                }
            }
            return(isSharingTableWithBase);
        }
        public static void RemoveAllForeignKeyConstraintsForColumn(
            EntityType table, EdmProperty column, DbDatabaseMapping databaseMapping)
        {
            DebugCheck.NotNull(table);
            DebugCheck.NotNull(column);
            DebugCheck.NotNull(databaseMapping);

            table.ForeignKeyBuilders
            .Where(fk => fk.DependentColumns.Contains(column))
            .ToArray()
            .Each(
                fk =>
            {
                table.RemoveForeignKey(fk);

                var copiedFk
                    = databaseMapping.Database.EntityTypes
                      .SelectMany(t => t.ForeignKeyBuilders)
                      .SingleOrDefault(fk2 => Equals(fk2.GetPreferredName(), fk.Name));

                if (copiedFk != null)
                {
                    copiedFk.Name = copiedFk.GetPreferredName();
                }
            });
        }
Пример #4
0
        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);
        }
        internal static void AssertValid(this DbDatabaseMapping databaseMapping, bool shouldThrow)
        {
            var storageItemMappingCollection = databaseMapping.ToStorageMappingItemCollection();
            IList <EdmSchemaError> errors;

            storageItemMappingCollection.GenerateEntitySetViews(out errors);

            if (errors.Any())
            {
                var errorMessage = new StringBuilder();
                errorMessage.AppendLine();

                foreach (var error in errors)
                {
                    errorMessage.AppendLine(error.ToString());
                }

                if (shouldThrow)
                {
                    throw new MappingException(errorMessage.ToString());
                }

                Assert.True(false, errorMessage.ToString());
            }
        }
Пример #6
0
        private static void ConfigureUnconfiguredDerivedTypes(
            DbDatabaseMapping databaseMapping,
            ICollection <EntitySet> entitySets,
            DbProviderManifest providerManifest,
            EntityType entityType,
            IList <EntityTypeConfiguration> sortedEntityConfigurations)
        {
            var derivedTypes = databaseMapping.Model.GetDerivedTypes(entityType).ToList();

            while (derivedTypes.Count > 0)
            {
                var currentType = derivedTypes[0];
                derivedTypes.RemoveAt(0);

                // Configure the derived type if it is not abstract and is not otherwise configured
                // if the type is not configured, then also run through that type's derived types
                if (!currentType.Abstract &&
                    sortedEntityConfigurations.All(etc => etc.ClrType != currentType.GetClrType()))
                {
                    // run through mapping configuration to make sure property mappings point to where the base type is now mapping them
                    EntityTypeConfiguration.ConfigureUnconfiguredType(databaseMapping, entitySets, providerManifest, currentType, new Dictionary <string, object>());
                    derivedTypes.AddRange(databaseMapping.Model.GetDerivedTypes(currentType));
                }
            }
        }
        private static void ConfigureDependentKeys(DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
        {
            DebugCheck.NotNull(databaseMapping);
            DebugCheck.NotNull(providerManifest);

            foreach (var foreignKeyConstraint in databaseMapping.Database.EntityTypes.SelectMany(t => t.ForeignKeyBuilders))
            {
                foreignKeyConstraint
                .DependentColumns
                .Each(
                    (c, i) =>
                {
                    var primitivePropertyConfiguration =
                        c.GetConfiguration() as PrimitivePropertyConfiguration;

                    if ((primitivePropertyConfiguration != null) &&
                        (primitivePropertyConfiguration.ColumnType != null))
                    {
                        return;
                    }

                    var principalColumn = foreignKeyConstraint.PrincipalTable.KeyProperties.ElementAt(i);

                    c.PrimitiveType = providerManifest.GetStoreTypeFromName(principalColumn.TypeName);

                    c.CopyFrom(principalColumn);
                });
            }
        }
        internal void Configure(
            EntityType entityType,
            DbDatabaseMapping databaseMapping,
            DbProviderManifest providerManifest)
        {
            DebugCheck.NotNull(entityType);
            DebugCheck.NotNull(databaseMapping);
            DebugCheck.NotNull(providerManifest);

            var entityTypeMapping
                = databaseMapping.GetEntityTypeMapping(entityType.GetClrType());

            if (entityTypeMapping != null)
            {
                VerifyAllCSpacePropertiesAreMapped(
                    databaseMapping.GetEntityTypeMappings(entityType).ToList(),
                    entityTypeMapping.EntityType.DeclaredProperties,
                    new List <EdmProperty>());
            }

            ConfigurePropertyMappings(databaseMapping, entityType, providerManifest);
            ConfigureIndexes(databaseMapping, entityType);
            ConfigureAssociationMappings(databaseMapping, entityType, providerManifest);
            ConfigureDependentKeys(databaseMapping, providerManifest);
            ConfigureModificationStoredProcedures(databaseMapping, entityType, providerManifest);
        }
        protected static StorageEntityTypeMapping GetEntityTypeMappingInHierarchy(
            DbDatabaseMapping databaseMapping, EntityType entityType)
        {
            DebugCheck.NotNull(databaseMapping);
            DebugCheck.NotNull(entityType);

            var entityTypeMapping = databaseMapping.GetEntityTypeMapping(entityType);

            if (entityTypeMapping == null)
            {
                var entitySetMapping =
                    databaseMapping.GetEntitySetMapping(databaseMapping.Model.GetEntitySet(entityType));

                if (entitySetMapping != null)
                {
                    entityTypeMapping = entitySetMapping
                                        .EntityTypeMappings
                                        .First(
                        etm => entityType.DeclaredProperties.All(
                            dp => etm.MappingFragments.First()
                            .ColumnMappings.Select(pm => pm.PropertyPath.First()).Contains(dp)));
                }
            }

            if (entityTypeMapping == null)
            {
                throw Error.UnmappedAbstractType(entityType.GetClrType());
            }

            return(entityTypeMapping);
        }
        internal void ConfigureTablesAndConditions(
            EntityTypeMapping entityTypeMapping,
            DbDatabaseMapping databaseMapping,
            DbProviderManifest providerManifest)
        {
            DebugCheck.NotNull(databaseMapping);
            DebugCheck.NotNull(providerManifest);

            var entityType
                = (entityTypeMapping != null)
                      ? entityTypeMapping.EntityType
                      : databaseMapping.Model.GetEntityType(ClrType);

            if (_entityMappingConfigurations.Any())
            {
                for (var i = 0; i < _entityMappingConfigurations.Count; i++)
                {
                    _entityMappingConfigurations[i]
                    .Configure(
                        databaseMapping,
                        providerManifest,
                        entityType,
                        ref entityTypeMapping,
                        IsMappingAnyInheritedProperty(entityType),
                        i,
                        _entityMappingConfigurations.Count,
                        _annotations);
                }
            }
            else
            {
                ConfigureUnconfiguredType(databaseMapping, providerManifest, entityType, _annotations);
            }
        }
Пример #11
0
 internal void ApplyMapping(DbDatabaseMapping databaseMapping)
 {
     foreach (IConvention mappingConvention in this._conceptualToStoreMappingConventions)
     {
         (mappingConvention as IDbMappingConvention)?.Apply(databaseMapping);
     }
 }
Пример #12
0
 private static void GenerateAssociationTypes(DbDatabaseMapping databaseMapping)
 {
     foreach (AssociationType associationType in databaseMapping.Model.AssociationTypes)
     {
         new AssociationTypeMappingGenerator(databaseMapping.ProviderManifest).Generate(associationType, databaseMapping);
     }
 }
Пример #13
0
        internal static bool AnyBaseTypeToTableWithoutColumnCondition(
            DbDatabaseMapping databaseMapping, EntityType entityType, EntityType table,
            EdmProperty column)
        {
            var baseType = entityType.BaseType;

            while (baseType != null)
            {
                if (!baseType.Abstract)
                {
                    var baseTypeTableFragments
                        = databaseMapping.GetEntityTypeMappings((EntityType)baseType)
                          .SelectMany(etm => etm.MappingFragments)
                          .Where(tmf => tmf.Table == table)
                          .ToList();

                    if (baseTypeTableFragments.Any() &&
                        baseTypeTableFragments
                        .SelectMany(etmf => etmf.ColumnConditions)
                        .All(cc => cc.Column != column))
                    {
                        return(true);
                    }
                }

                baseType = baseType.BaseType;
            }

            return(false);
        }
Пример #14
0
        internal void Configure(
            AssociationSetMapping associationSetMapping,
            DbDatabaseMapping databaseMapping,
            DbProviderManifest providerManifest)
        {
            DebugCheck.NotNull(associationSetMapping);
            DebugCheck.NotNull(databaseMapping);
            DebugCheck.NotNull(providerManifest);

            // We may apply configuration twice from two different NavigationPropertyConfiguration objects,
            // but that should be okay since they were validated as consistent above.
            // We still apply twice because each object may have different pieces of the full configuration.
            if (AssociationMappingConfiguration != null)
            {
                // This may replace a configuration previously set, but that's okay since we validated
                // consistency when processing the configuration above.
                associationSetMapping.SetConfiguration(this);

                AssociationMappingConfiguration
                .Configure(associationSetMapping, databaseMapping.Database, _navigationProperty);
            }

            if (_modificationStoredProceduresConfiguration != null)
            {
                if (associationSetMapping.ModificationFunctionMapping == null)
                {
                    new ModificationFunctionMappingGenerator(providerManifest)
                    .Generate(associationSetMapping, databaseMapping);
                }

                _modificationStoredProceduresConfiguration
                .Configure(associationSetMapping.ModificationFunctionMapping, providerManifest);
            }
        }
Пример #15
0
        public void UpdateMapping_updates_msl()
        {
            var edmx            = XDocument.Parse(EdmxTemplate);
            var databaseMapping =
                new DbDatabaseMapping
            {
                Database = new EdmModel(DataSpace.SSpace),
                Model    = new EdmModel(DataSpace.SSpace),
            };
            var model = new DbModel(databaseMapping, new DbModelBuilder());

            databaseMapping.AddEntityContainerMapping(
                new EntityContainerMapping(
                    databaseMapping.Model.Containers.Single(),
                    databaseMapping.Database.Containers.Single(),
                    null, false, false));

            new EdmxHelper(edmx).UpdateMapping(model);

            var storageModelsElements =
                edmx.Descendants(EdmxV3Namespace + "Mappings").Single();

            Assert.Equal(1, storageModelsElements.Elements().Count());
            Assert.Equal(
                XName.Get("Mapping", SchemaManager.GetMSLNamespaceName(EntityFrameworkVersion.Version3)),
                storageModelsElements.Elements().Single().Name);
        }
Пример #16
0
        public void Serialize(DbDatabaseMapping databaseMapping, DbProviderInfo providerInfo, XmlWriter xmlWriter)
        {
            DebugCheck.NotNull(xmlWriter);
            DebugCheck.NotNull(databaseMapping);
            DebugCheck.NotNull(providerInfo);
            Debug.Assert(databaseMapping.Model != null);
            Debug.Assert(databaseMapping.Database != null);

            _xmlWriter       = xmlWriter;
            _databaseMapping = databaseMapping;
            _version         = databaseMapping.Model.SchemaVersion;
            _providerInfo    = providerInfo;
            _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();
        }
Пример #17
0
        private void ConfigureEntityTypes(DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
        {
            var sortedEntityConfigurations =
                SortEntityConfigurationsByInheritance(databaseMapping);

            foreach (var entityTypeConfiguration in sortedEntityConfigurations)
            {
                var entityTypeMapping
                    = databaseMapping.GetEntityTypeMapping(entityTypeConfiguration.ClrType);

                entityTypeConfiguration.ConfigureTablesAndConditions(
                    entityTypeMapping, databaseMapping, providerManifest);

                // run through all unconfigured derived types of the current entityType to make sure the property mappings now point to the right places
                ConfigureUnconfiguredDerivedTypes(
                    databaseMapping,
                    providerManifest,
                    databaseMapping.Model.GetEntityType(entityTypeConfiguration.ClrType),
                    sortedEntityConfigurations);
            }

            new EntityMappingService(databaseMapping).Configure();

            foreach (var entityType in databaseMapping.Model.GetEntityTypes().Where(e => e.GetConfiguration() != null))
            {
                var entityTypeConfiguration = (EntityTypeConfiguration)entityType.GetConfiguration();

                entityTypeConfiguration.Configure(entityType, databaseMapping, providerManifest);
            }
        }
        private void ConfigureAssociationMappings(
            DbDatabaseMapping databaseMapping, EntityType entityType, DbProviderManifest providerManifest)
        {
            DebugCheck.NotNull(databaseMapping);
            DebugCheck.NotNull(entityType);
            DebugCheck.NotNull(providerManifest);

            foreach (var configuration in _navigationPropertyConfigurations)
            {
                var propertyInfo = configuration.Key;
                var navigationPropertyConfiguration = configuration.Value;
                var navigationProperty = entityType.GetNavigationProperty(propertyInfo);

                if (navigationProperty == null)
                {
                    throw Error.NavigationPropertyNotFound(propertyInfo.Name, entityType.Name);
                }

                var associationSetMapping
                    = databaseMapping.GetAssociationSetMappings()
                      .SingleOrDefault(asm => asm.AssociationSet.ElementType == navigationProperty.Association);

                if (associationSetMapping != null)
                {
                    navigationPropertyConfiguration.Configure(associationSetMapping, databaseMapping, providerManifest);
                }
            }
        }
        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;
        }
Пример #20
0
        internal void Configure(DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
        {
            DebugCheck.NotNull(databaseMapping);
            DebugCheck.NotNull(providerManifest);

            foreach (var structuralTypeConfiguration
                     in databaseMapping.Model.ComplexTypes
                     .Select(ct => ct.GetConfiguration())
                     .Cast <StructuralTypeConfiguration>()
                     .Where(c => c != null))
            {
                structuralTypeConfiguration.ConfigurePropertyMappings(
                    databaseMapping.GetComplexPropertyMappings(structuralTypeConfiguration.ClrType).ToList(),
                    providerManifest);
            }

            ConfigureEntityTypes(databaseMapping, databaseMapping.Model.Container.EntitySets, providerManifest);
            RemoveRedundantColumnConditions(databaseMapping);
            RemoveRedundantTables(databaseMapping);
            ConfigureTables(databaseMapping.Database);
            ConfigureDefaultSchema(databaseMapping);
            UniquifyFunctionNames(databaseMapping);
            ConfigureFunctionParameters(databaseMapping);
            RemoveDuplicateTphColumns(databaseMapping);
        }
Пример #21
0
        public void Initialize_should_add_default_entity_container_mapping()
        {
            var databaseMapping = new DbDatabaseMapping()
                                  .Initialize(new EdmModel().Initialize(), new EdmModel());

            Assert.Equal(1, databaseMapping.EntityContainerMappings.Count);
        }
Пример #22
0
        private static void RemoveRedundantTables(DbDatabaseMapping databaseMapping)
        {
            DebugCheck.NotNull(databaseMapping);

            var tables
                = (from t in databaseMapping.Database.EntityTypes
                   where databaseMapping.GetEntitySetMappings()
                   .SelectMany(esm => esm.EntityTypeMappings)
                   .SelectMany(etm => etm.MappingFragments)
                   .All(etmf => etmf.Table != t) &&
                   databaseMapping.GetAssociationSetMappings().All(asm => asm.Table != t)
                   select t).ToList();

            tables.Each(
                t =>
            {
                var tableName = t.GetTableName();

                if (tableName != null)
                {
                    throw Error.OrphanedConfiguredTableDetected(tableName);
                }

                databaseMapping.Database.RemoveEntityType(t);

                // Remove any FKs on the removed table
                var associationTypes
                    = databaseMapping.Database.AssociationTypes
                      .Where(at => at.SourceEnd.GetEntityType() == t ||
                             at.TargetEnd.GetEntityType() == t)
                      .ToList();

                associationTypes.Each(at => databaseMapping.Database.RemoveAssociationType(at));
            });
        }
        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, ProviderRegistry.Sql2008_ProviderManifest, entityTypeMapping.EntityType,
                ref entityTypeMapping, false, 0, 1,
                new Dictionary <string, object>());

            Assert.Equal("Foo", table.GetTableName().Name);
        }
Пример #24
0
        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);
        }
Пример #25
0
        private void GenerateIndependentAssociationType(
            AssociationType associationType,
            DbDatabaseMapping databaseMapping)
        {
            AssociationEndMember principalEnd;
            AssociationEndMember dependentEnd;

            if (!associationType.TryGuessPrincipalAndDependentEnds(out principalEnd, out dependentEnd))
            {
                if (!associationType.IsPrincipalConfigured())
                {
                    throw Error.UnableToDeterminePrincipal((object)EntityTypeExtensions.GetClrType(associationType.SourceEnd.GetEntityType()), (object)EntityTypeExtensions.GetClrType(associationType.TargetEnd.GetEntityType()));
                }
                principalEnd = associationType.SourceEnd;
                dependentEnd = associationType.TargetEnd;
            }
            EntityTypeMapping     mappingInHierarchy = StructuralTypeMappingGenerator.GetEntityTypeMappingInHierarchy(databaseMapping, dependentEnd.GetEntityType());
            EntityType            table = mappingInHierarchy.MappingFragments.First <MappingFragment>().Table;
            AssociationSetMapping associationSetMapping = AssociationTypeMappingGenerator.GenerateAssociationSetMapping(associationType, databaseMapping, principalEnd, dependentEnd, table);

            this.GenerateIndependentForeignKeyConstraint(databaseMapping, principalEnd.GetEntityType(), dependentEnd.GetEntityType(), table, associationSetMapping, associationSetMapping.SourceEndMapping, associationType.Name, principalEnd, false);
            foreach (EdmProperty keyProperty in dependentEnd.GetEntityType().KeyProperties())
            {
                associationSetMapping.TargetEndMapping.AddPropertyMapping(new ScalarPropertyMapping(keyProperty, mappingInHierarchy.GetPropertyMapping(keyProperty).ColumnProperty));
            }
        }
Пример #26
0
        private static EntityType FindTableForTemporaryExtraPropertyMapping(
            DbDatabaseMapping databaseMapping,
            EntityType entityType,
            EntityType fromTable,
            EntityType toTable,
            ColumnMappingBuilder pm)
        {
            var extraTable = fromTable;

            if (fromTable == toTable)
            {
                extraTable = databaseMapping.Database.AddTable(entityType.Name, fromTable);
            }
            else if (entityType.BaseType == null)
            {
                extraTable = fromTable;
            }
            else
            {
                // find where the base mappings are and put them in that table
                extraTable = FindBaseTableForExtraPropertyMapping(databaseMapping, entityType, pm);
                if (extraTable == null)
                {
                    extraTable = fromTable;
                }
            }
            return(extraTable);
        }
Пример #27
0
        public void Configure_should_configure_mapping()
        {
            var manyToManyAssociationMappingConfiguration = new ManyToManyAssociationMappingConfiguration();

            manyToManyAssociationMappingConfiguration.ToTable("Foo");

            var mockPropertyInfo = new MockPropertyInfo(typeof(AType1), "N");

            var navigationPropertyConfiguration
                = new NavigationPropertyConfiguration(mockPropertyInfo)
                {
                AssociationMappingConfiguration = manyToManyAssociationMappingConfiguration
                };

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

            var associationSetMapping = databaseMapping.AddAssociationSetMapping(
                new AssociationSet("AS", new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace)), new EntitySet());

            var dependentTable = databaseMapping.Database.AddTable("T");

            associationSetMapping.StoreEntitySet = databaseMapping.Database.GetEntitySet(dependentTable);
            associationSetMapping.AssociationSet.ElementType.SetConfiguration(navigationPropertyConfiguration);

            associationSetMapping.SourceEndMapping.AssociationEnd = new AssociationEndMember("S", new EntityType("E", "N", DataSpace.CSpace));
            associationSetMapping.SourceEndMapping.AssociationEnd.SetClrPropertyInfo(mockPropertyInfo);

            navigationPropertyConfiguration.Configure(associationSetMapping, databaseMapping, ProviderRegistry.Sql2008_ProviderManifest);

            Assert.Equal("Foo", associationSetMapping.Table.GetTableName().Name);
        }
Пример #28
0
        private static EntityType FindBaseTableForExtraPropertyMapping(
            DbDatabaseMapping databaseMapping, EntityType entityType, ColumnMappingBuilder pm)
        {
            var baseType = (EntityType)entityType.BaseType;

            StorageMappingFragment baseFragment = null;

            while (baseType != null &&
                   baseFragment == null)
            {
                var baseMapping = databaseMapping.GetEntityTypeMapping(baseType);
                if (baseMapping != null)
                {
                    baseFragment =
                        baseMapping.MappingFragments.SingleOrDefault(
                            f => f.ColumnMappings.Any(bpm => bpm.PropertyPath.SequenceEqual(pm.PropertyPath)));

                    if (baseFragment != null)
                    {
                        return(baseFragment.Table);
                    }
                }
                baseType = (EntityType)baseType.BaseType;
            }
            return(null);
        }
Пример #29
0
        internal static PropertyAssertions Assert <TStructuralType>(
            this DbDatabaseMapping databaseMapping, Expression <Func <TStructuralType, object> > propertyExpression)
        {
            var structuralType
                = databaseMapping.Model.Namespaces.Single().NamespaceItems
                  .OfType <StructuralType>()
                  .Single(
                      i => i.Annotations.Any(
                          a => a.Name == "ClrType" &&
                          (Type)a.Value == typeof(TStructuralType)));

            var property
                = databaseMapping.Model.Namespaces.Single().NamespaceItems.OfType <StructuralType>()
                  .Where(
                      i => i.Annotations.Any(
                          a => a.Name == "ClrType" &&
                          ((Type)a.Value).IsAssignableFrom(typeof(TStructuralType))))
                  .SelectMany(th => th.Members.OfType <EdmProperty>()).Distinct().Single(
                      i => i.Annotations.Any(
                          a => a.Name == "ClrPropertyInfo" &&
                          (PropertyInfo)a.Value == GetPropertyInfo(propertyExpression)));

            var columns
                = databaseMapping.EntityContainerMappings.Single().EntitySetMappings
                  .SelectMany(esm => esm.EntityTypeMappings)
                  .Where(etm => !(structuralType is EntityType) || etm.EntityType == structuralType)
                  .SelectMany(etm => etm.MappingFragments)
                  .SelectMany(tmf => tmf.ColumnMappings)
                  .Where(pm => pm.PropertyPath.Contains(property))
                  .Select(pm => pm.ColumnProperty);

            return(new PropertyAssertions(property, columns.First()));
        }
Пример #30
0
 private static IEnumerable <Tuple <ModificationFunctionMemberPath, EdmProperty> > GetIndependentFkColumns(
     EntityType entityType,
     DbDatabaseMapping databaseMapping)
 {
     foreach (AssociationSetMapping associationSetMapping in databaseMapping.GetAssociationSetMappings())
     {
         AssociationType associationType = associationSetMapping.AssociationSet.ElementType;
         if (!associationType.IsManyToMany())
         {
             AssociationEndMember _;
             AssociationEndMember dependentEnd;
             if (!associationType.TryGuessPrincipalAndDependentEnds(out _, out dependentEnd))
             {
                 dependentEnd = associationType.TargetEnd;
             }
             EntityType dependentEntityType = dependentEnd.GetEntityType();
             if (dependentEntityType == entityType || ModificationFunctionMappingGenerator.GetParents(entityType).Contains <EntityType>(dependentEntityType))
             {
                 EndPropertyMapping endPropertyMapping = associationSetMapping.TargetEndMapping.AssociationEnd != dependentEnd ? associationSetMapping.TargetEndMapping : associationSetMapping.SourceEndMapping;
                 foreach (ScalarPropertyMapping propertyMapping in endPropertyMapping.PropertyMappings)
                 {
                     yield return(Tuple.Create <ModificationFunctionMemberPath, EdmProperty>(new ModificationFunctionMemberPath((IEnumerable <EdmMember>) new EdmMember[2]
                     {
                         (EdmMember)propertyMapping.Property,
                         (EdmMember)dependentEnd
                     }, associationSetMapping.AssociationSet), propertyMapping.Column));
                 }
             }
         }
     }
 }
 internal static string SerializeToString(DbDatabaseMapping databaseMapping)
 {
     var edmx = new StringBuilder();
     new EdmxSerializer().Serialize(databaseMapping, databaseMapping.Database.GetProviderInfo(),
                                    XmlWriter.Create(edmx, new XmlWriterSettings { Indent = true }));
     return edmx.ToString();
 }
        private void GenerateDiscriminators(DbDatabaseMapping databaseMapping)
        {
            Contract.Requires(databaseMapping != null);

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

                var discriminatorColumn
                    = entitySetMapping
                        .EntityTypeMappings
                        .First()
                        .TypeMappingFragments
                        .Single()
                        .Table
                        .AddColumn(DiscriminatorColumnName);

                InitializeDefaultDiscriminatorColumn(discriminatorColumn);

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

                    entityTypeMappingFragment.SetDefaultDiscriminator(discriminatorColumn);

                    entityTypeMappingFragment
                        .AddDiscriminatorCondition(discriminatorColumn, entityTypeMapping.EntityType.Name);
                }
            }
        }
        private static DbDatabaseMapping InitializeDatabaseMapping(EdmModel model)
        {
            Contract.Requires(model != null);

            var databaseMapping = new DbDatabaseMapping().Initialize(
                model, new DbDatabaseMetadata().Initialize(model.Version));

            databaseMapping.EntityContainerMappings.Single().EntityContainer = model.Containers.Single();

            return databaseMapping;
        }
        /// <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)
        {
            Contract.Requires(databaseMapping != null);

            _providerInfo = databaseMapping.Database.GetProviderInfo();

            _metadataWorkspace = databaseMapping.ToMetadataWorkspace();

            _assemblies = databaseMapping.Model.GetClrTypes().Select(t => t.Assembly).Distinct().ToList();

            Contract.Assert(
                databaseMapping.Model.Containers.Count() == 1, "Expecting Code First to create only one container.");
            _defaultContainerName = databaseMapping.Model.Containers.First().Name;
        }
        private void GenerateEntityTypes(EdmModel model, DbDatabaseMapping databaseMapping)
        {
            Contract.Requires(model != null);
            Contract.Requires(databaseMapping != null);

            foreach (var entityType in model.GetEntityTypes())
            {
                if (!entityType.IsAbstract)
                {
                    new EntityTypeMappingGenerator(_providerManifest).
                        Generate(entityType, databaseMapping);
                }
            }
        }
        protected static DbEntityTypeMapping GetEntityTypeMappingInHierarchy(
            DbDatabaseMapping databaseMapping, EdmEntityType entityType)
        {
            Contract.Requires(databaseMapping != null);
            Contract.Requires(entityType != null);

            var entityTypeMapping = databaseMapping.GetEntityTypeMapping(entityType);

            if (entityTypeMapping == null)
            {
                var entitySetMapping =
                    databaseMapping.GetEntitySetMapping(databaseMapping.Model.GetEntitySet(entityType));

                if (entitySetMapping != null)
                {
                    entityTypeMapping = entitySetMapping
                        .EntityTypeMappings
                        .First(
                            etm => entityType.DeclaredProperties.All(
                                dp => etm.TypeMappingFragments.First()
                                          .PropertyMappings.Select(pm => pm.PropertyPath.First()).Contains(dp)));
                }
            }

            if (entityTypeMapping == null)
            {
                throw Error.UnmappedAbstractType(entityType.GetClrType());
            }

            return entityTypeMapping;
        }
 internal static bool EdmxIsEqualTo(this DbDatabaseMapping databaseMapping,
                                    DbDatabaseMapping otherDatabaseMapping)
 {
     return SerializeToString(databaseMapping) == SerializeToString(otherDatabaseMapping);
 }
        private void GenerateAssociationTypes(EdmModel model, DbDatabaseMapping databaseMapping)
        {
            Contract.Requires(model != null);
            Contract.Requires(databaseMapping != null);

            foreach (var associationType in model.GetAssociationTypes())
            {
                new AssociationTypeMappingGenerator(_providerManifest)
                    .Generate(associationType, databaseMapping);
            }
        }