Example #1
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);
            }
        }
Example #2
0
        private static void UpdatePrincipalTables(
            DbDatabaseMapping databaseMapping,
            EntityType toTable,
            bool removeFks,
            AssociationType associationType,
            EntityType et)
        {
            List <AssociationEndMember> associationEndMemberList = new List <AssociationEndMember>();
            AssociationEndMember        principalEnd;
            AssociationEndMember        dependentEnd;

            if (associationType.TryGuessPrincipalAndDependentEnds(out principalEnd, out dependentEnd))
            {
                associationEndMemberList.Add(principalEnd);
            }
            else if (associationType.SourceEnd.RelationshipMultiplicity == RelationshipMultiplicity.Many && associationType.TargetEnd.RelationshipMultiplicity == RelationshipMultiplicity.Many)
            {
                associationEndMemberList.Add(associationType.SourceEnd);
                associationEndMemberList.Add(associationType.TargetEnd);
            }
            else
            {
                associationEndMemberList.Add(associationType.SourceEnd);
            }
            foreach (AssociationEndMember associationEnd in associationEndMemberList)
            {
                if (associationEnd.GetEntityType() == et)
                {
                    IEnumerable <KeyValuePair <EntityType, IEnumerable <EdmProperty> > > keyValuePairs;
                    if (associationType.Constraint != null)
                    {
                        EntityType entityType = associationType.GetOtherEnd(associationEnd).GetEntityType();
                        keyValuePairs = databaseMapping.Model.GetSelfAndAllDerivedTypes(entityType).Select <EntityType, EntityTypeMapping>((Func <EntityType, EntityTypeMapping>)(t => databaseMapping.GetEntityTypeMapping(t))).Where <EntityTypeMapping>((Func <EntityTypeMapping, bool>)(dm => dm != null)).SelectMany <EntityTypeMapping, MappingFragment>((Func <EntityTypeMapping, IEnumerable <MappingFragment> >)(dm => dm.MappingFragments.Where <MappingFragment>((Func <MappingFragment, bool>)(tmf => associationType.Constraint.ToProperties.All <EdmProperty>((Func <EdmProperty, bool>)(p => tmf.ColumnMappings.Any <ColumnMappingBuilder>((Func <ColumnMappingBuilder, bool>)(pm => pm.PropertyPath.First <EdmProperty>() == p)))))))).Distinct <MappingFragment>((Func <MappingFragment, MappingFragment, bool>)((f1, f2) => f1.Table == f2.Table)).Select <MappingFragment, KeyValuePair <EntityType, IEnumerable <EdmProperty> > >((Func <MappingFragment, KeyValuePair <EntityType, IEnumerable <EdmProperty> > >)(df => new KeyValuePair <EntityType, IEnumerable <EdmProperty> >(df.Table, df.ColumnMappings.Where <ColumnMappingBuilder>((Func <ColumnMappingBuilder, bool>)(pm => associationType.Constraint.ToProperties.Contains(pm.PropertyPath.First <EdmProperty>()))).Select <ColumnMappingBuilder, EdmProperty>((Func <ColumnMappingBuilder, EdmProperty>)(pm => pm.ColumnProperty)))));
                    }
                    else
                    {
                        AssociationSetMapping associationSetMapping = databaseMapping.EntityContainerMappings.Single <EntityContainerMapping>().AssociationSetMappings.Single <AssociationSetMapping>((Func <AssociationSetMapping, bool>)(asm => asm.AssociationSet.ElementType == associationType));
                        keyValuePairs = (IEnumerable <KeyValuePair <EntityType, IEnumerable <EdmProperty> > >) new KeyValuePair <EntityType, IEnumerable <EdmProperty> >[1]
                        {
                            new KeyValuePair <EntityType, IEnumerable <EdmProperty> >(associationSetMapping.Table, (associationSetMapping.SourceEndMapping.AssociationEnd == associationEnd ? (IEnumerable <ScalarPropertyMapping>)associationSetMapping.SourceEndMapping.PropertyMappings : (IEnumerable <ScalarPropertyMapping>)associationSetMapping.TargetEndMapping.PropertyMappings).Select <ScalarPropertyMapping, EdmProperty>((Func <ScalarPropertyMapping, EdmProperty>)(pm => pm.Column)))
                        };
                    }
                    foreach (KeyValuePair <EntityType, IEnumerable <EdmProperty> > keyValuePair in keyValuePairs)
                    {
                        KeyValuePair <EntityType, IEnumerable <EdmProperty> > tableInfo = keyValuePair;
                        foreach (ForeignKeyBuilder foreignKeyBuilder in tableInfo.Key.ForeignKeyBuilders.Where <ForeignKeyBuilder>((Func <ForeignKeyBuilder, bool>)(fk => fk.DependentColumns.SequenceEqual <EdmProperty>(tableInfo.Value))).ToArray <ForeignKeyBuilder>())
                        {
                            if (removeFks)
                            {
                                tableInfo.Key.RemoveForeignKey(foreignKeyBuilder);
                            }
                            else if (foreignKeyBuilder.GetAssociationType() == null || foreignKeyBuilder.GetAssociationType() == associationType)
                            {
                                foreignKeyBuilder.PrincipalTable = toTable;
                            }
                        }
                    }
                }
            }
        }
Example #3
0
        internal override void Configure(
            AssociationSetMapping associationSetMapping, EdmModel database, PropertyInfo navigationProperty)
        {
            DebugCheck.NotNull(associationSetMapping);
            DebugCheck.NotNull(database);
            DebugCheck.NotNull(navigationProperty);

            var table = associationSetMapping.Table;

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

            var sourceEndIsPrimaryConfiguration
                = navigationProperty.IsSameAs(
                    associationSetMapping.SourceEndMapping.AssociationEnd.GetClrPropertyInfo());

            ConfigureColumnNames(
                sourceEndIsPrimaryConfiguration ? _leftKeyColumnNames : _rightKeyColumnNames,
                associationSetMapping.SourceEndMapping.PropertyMappings.ToList());

            ConfigureColumnNames(
                sourceEndIsPrimaryConfiguration ? _rightKeyColumnNames : _leftKeyColumnNames,
                associationSetMapping.TargetEndMapping.PropertyMappings.ToList());

            foreach (var annotation in _annotations)
            {
                table.AddAnnotation(XmlConstants.CustomAnnotationPrefix + annotation.Key, annotation.Value);
            }
        }
Example #4
0
        private static AssociationSetMapping BuildAssociationSetMapping(
            CollapsibleEntityAssociationSets collapsibleItem,
            EntityContainerMapping entityContainerMapping,
            SimpleMappingContext mappingContext)
        {
            Debug.Assert(collapsibleItem != null, "collapsibleItem != null");
            Debug.Assert(entityContainerMapping != null, "entityContainerMapping != null");
            Debug.Assert(mappingContext != null, "mappingContext != null");

            var modelAssociationSet = mappingContext[collapsibleItem];

            if (modelAssociationSet.ElementType.IsForeignKey)
            {
                return(null);
            }

            var associationSetMapping = new AssociationSetMapping(
                modelAssociationSet, collapsibleItem.EntitySet, entityContainerMapping);

            var count = collapsibleItem.AssociationSets.Count;

            if (count > 0)
            {
                associationSetMapping.SourceEndMapping = BuildEndPropertyMapping(
                    collapsibleItem.GetStoreAssociationSetEnd(0).AssociationSetEnd, mappingContext);
            }
            if (count > 1)
            {
                associationSetMapping.TargetEndMapping = BuildEndPropertyMapping(
                    collapsibleItem.GetStoreAssociationSetEnd(1).AssociationSetEnd, mappingContext);
            }

            return(associationSetMapping);
        }
Example #5
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));
            }
        }
Example #6
0
        private IEnumerable <EdmProperty> GenerateIndependentForeignKeyColumns(
            EntityType principalEntityType,
            EntityType dependentEntityType,
            AssociationSetMapping associationSetMapping,
            EndPropertyMapping associationEndMapping,
            EntityType dependentTable,
            bool isPrimaryKeyColumn,
            NavigationProperty principalNavigationProperty)
        {
            foreach (EdmProperty keyProperty in principalEntityType.KeyProperties())
            {
                string      columnName       = (principalNavigationProperty != null ? principalNavigationProperty.Name : principalEntityType.Name) + "_" + keyProperty.Name;
                EdmProperty foreignKeyColumn = this.MapTableColumn(keyProperty, columnName, false);
                dependentTable.AddColumn(foreignKeyColumn);
                if (isPrimaryKeyColumn)
                {
                    dependentTable.AddKeyMember((EdmMember)foreignKeyColumn);
                }
                foreignKeyColumn.Nullable = associationEndMapping.AssociationEnd.IsOptional() || associationEndMapping.AssociationEnd.IsRequired() && dependentEntityType.BaseType != null;
                foreignKeyColumn.StoreGeneratedPattern = StoreGeneratedPattern.None;
                yield return(foreignKeyColumn);

                associationEndMapping.AddPropertyMapping(new ScalarPropertyMapping(keyProperty, foreignKeyColumn));
                if (foreignKeyColumn.Nullable)
                {
                    associationSetMapping.AddCondition((ConditionPropertyMapping) new IsNullConditionMapping(foreignKeyColumn, false));
                }
            }
        }
Example #7
0
        public void Configure_should_rename_columns_when_right_keys_configured()
        {
            var database = new EdmModel(DataSpace.CSpace);

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

            var column = new EdmProperty("C", TypeUsage.Create(new PrimitiveType()
            {
                DataSpace = DataSpace.SSpace
            }));

            associationSetMapping.TargetEndMapping.AddPropertyMapping(new ScalarPropertyMapping(new EdmProperty("PK"), column));

            var manyToManyAssociationMappingConfiguration
                = new ManyToManyAssociationMappingConfiguration();

            manyToManyAssociationMappingConfiguration.MapRightKey("NewName");

            var mockPropertyInfo = new MockPropertyInfo();

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

            manyToManyAssociationMappingConfiguration.Configure(associationSetMapping, database, mockPropertyInfo);

            Assert.Equal("NewName", column.Name);
        }
Example #8
0
        public void Configure_should_rename_table_when_table_configured()
        {
            var database = new EdmModel(DataSpace.SSpace);
            var table    = database.AddTable("OriginalName");

            var associationSetMapping
                = new AssociationSetMapping(
                      new AssociationSet("AS", new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace)),
                      database.GetEntitySet(table))
                  .Initialize();

            var manyToManyAssociationMappingConfiguration
                = new ManyToManyAssociationMappingConfiguration();

            manyToManyAssociationMappingConfiguration.ToTable("NewName");

            var mockPropertyInfo = new MockPropertyInfo();

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

            manyToManyAssociationMappingConfiguration.Configure(associationSetMapping, database, mockPropertyInfo);

            Assert.Equal("NewName", table.GetTableName().Name);
            Assert.Same(manyToManyAssociationMappingConfiguration, table.GetConfiguration());
        }
        private static bool TryGetWithRelationship(
            AssociationSetMapping colocatedAssociationSetMap,
            EntitySetBase thisExtent,
            MemberPath sRootNode,
            ref List <SlotInfo> foreignKeySlots,
            out WithRelationship withRelationship)
        {
            DebugCheck.NotNull(foreignKeySlots);
            withRelationship = null;

            //Get the map for foreign key end
            var foreignKeyEndMap = GetForeignKeyEndMapFromAssocitionMap(colocatedAssociationSetMap);

            if (foreignKeyEndMap == null ||
                foreignKeyEndMap.AssociationEnd.RelationshipMultiplicity == RelationshipMultiplicity.Many)
            {
                return(false);
            }

            var toEnd             = (AssociationEndMember)foreignKeyEndMap.AssociationEnd;
            var fromEnd           = MetadataHelper.GetOtherAssociationEnd(toEnd);
            var toEndEntityType   = (EntityType)((RefType)(toEnd.TypeUsage.EdmType)).ElementType;
            var fromEndEntityType = (EntityType)(((RefType)fromEnd.TypeUsage.EdmType).ElementType);

            // Get the member path for AssociationSet
            var associationSet = (AssociationSet)colocatedAssociationSetMap.Set;
            var prefix         = new MemberPath(associationSet, toEnd);

            // Collect the member paths for edm scalar properties that belong to the target entity key.
            // These will be used as part of WITH RELATIONSHIP.
            // Get the key properties from edm type since the query parser depends on the order of key members
            var propertyMaps = foreignKeyEndMap.PropertyMappings.Cast <ScalarPropertyMapping>();
            var toEndEntityKeyMemberPaths = new List <MemberPath>();

            foreach (EdmProperty edmProperty in toEndEntityType.KeyMembers)
            {
                var scalarPropertyMaps = propertyMaps.Where(propMap => (propMap.Property.Equals(edmProperty)));
                Debug.Assert(scalarPropertyMaps.Count() == 1, "Can't Map the same column multiple times in the same end");
                var scalarPropertyMap = scalarPropertyMaps.First();

                // Create SlotInfo for Freign Key member that needs to be projected.
                var sSlot            = new MemberProjectedSlot(new MemberPath(sRootNode, scalarPropertyMap.Column));
                var endMemberKeyPath = new MemberPath(prefix, edmProperty);
                toEndEntityKeyMemberPaths.Add(endMemberKeyPath);
                foreignKeySlots.Add(new SlotInfo(true, true, sSlot, endMemberKeyPath));
            }

            // Parent assignable from child: Ensures they are in the same hierarchy.
            if (thisExtent.ElementType.IsAssignableFrom(fromEndEntityType))
            {
                // Now create the WITH RELATIONSHIP with all the needed info.
                withRelationship = new WithRelationship(
                    associationSet, fromEnd, fromEndEntityType, toEnd, toEndEntityType, toEndEntityKeyMemberPaths);
                return(true);
            }
            else
            {
                return(false);
            }
        }
        private static void MoveAssociationSetMappingDependents(
            AssociationSetMapping associationSetMapping,
            EndPropertyMapping dependentMapping,
            EntitySet toSet,
            bool useExistingColumns)
        {
            DebugCheck.NotNull(associationSetMapping);
            DebugCheck.NotNull(dependentMapping);
            DebugCheck.NotNull(toSet);

            var toTable = toSet.ElementType;

            dependentMapping.PropertyMappings.Each(
                pm =>
            {
                var oldColumn = pm.Column;

                pm.Column
                    = TableOperations.MoveColumnAndAnyConstraints(
                          associationSetMapping.Table, toTable, oldColumn, useExistingColumns);

                associationSetMapping.Conditions
                .Where(cc => cc.Column == oldColumn)
                .Each(cc => cc.Column = pm.Column);
            });

            associationSetMapping.StoreEntitySet = toSet;
        }
Example #11
0
 public static AssociationSetMapping Initialize(
     this AssociationSetMapping associationSetMapping)
 {
     associationSetMapping.SourceEndMapping = new EndPropertyMapping();
     associationSetMapping.TargetEndMapping = new EndPropertyMapping();
     return(associationSetMapping);
 }
Example #12
0
        public static Dictionary <string, string> GetLookupPropertiesMappingDictionary(this Edmx edmx, Type entityClrType)
        {
            string entityName = entityClrType.Name;
            Dictionary <string, string> mappingDictionary = new Dictionary <string, string>();

            foreach (NavigationProperty navigationProperty in edmx.GetLookupProperties(entityClrType))
            {
                string relationship = GetAdjustedText(navigationProperty.Relationship);

                string fromRole = navigationProperty.FromRole;
                string toRole   = navigationProperty.ToRole;

                LinqToEdmx.Model.Conceptual.Association association = edmx.GetConceptualAssociation(relationship);

                LinqToEdmx.Model.Conceptual.AssociationEnd fromAssociation = edmx.GetConceptualAssociationEnd(relationship, fromRole);
                LinqToEdmx.Model.Conceptual.AssociationEnd toAssociation   = edmx.GetConceptualAssociationEnd(relationship, toRole);

                AssociationSetMapping entityTypesMappingAssociation = edmx.GetMappingAssociationSet(entityName, relationship);
                foreach (EndProperty endProperty in entityTypesMappingAssociation.EndProperties)
                {
                    if (endProperty.Name == toRole)
                    {
                        string columnName = endProperty.ScalarProperties[0].ColumnName;
                        mappingDictionary.Add(navigationProperty.Name, columnName);
                    }
                }
            }

            return(mappingDictionary);
        }
Example #13
0
        public void WriteAssociationSetMappingElement(AssociationSetMapping associationSetMapping)
        {
            DebugCheck.NotNull(associationSetMapping);

            _xmlWriter.WriteStartElement(MslConstructs.AssociationSetMappingElement);
            _xmlWriter.WriteAttributeString(
                MslConstructs.AssociationSetMappingNameAttribute, associationSetMapping.AssociationSet.Name);
            _xmlWriter.WriteAttributeString(
                MslConstructs.AssociationSetMappingTypeNameAttribute,
                _entityTypeNamespace + "." + associationSetMapping.AssociationSet.ElementType.Name);
            _xmlWriter.WriteAttributeString(
                MslConstructs.AssociationSetMappingStoreEntitySetAttribute, associationSetMapping.Table.Name);

            WriteAssociationEndMappingElement(associationSetMapping.SourceEndMapping);
            WriteAssociationEndMappingElement(associationSetMapping.TargetEndMapping);

            if (associationSetMapping.ModificationFunctionMapping != null)
            {
                WriteModificationFunctionMapping(associationSetMapping.ModificationFunctionMapping);
            }

            foreach (var conditionColumn in associationSetMapping.Conditions)
            {
                WriteConditionElement(conditionColumn);
            }

            _xmlWriter.WriteEndElement();
        }
Example #14
0
        internal override void Configure(
            AssociationSetMapping associationSetMapping,
            EdmModel database,
            PropertyInfo navigationProperty)
        {
            List <ScalarPropertyMapping> propertyMappings = associationSetMapping.SourceEndMapping.PropertyMappings.ToList <ScalarPropertyMapping>();

            if (this._tableName != null)
            {
                EntityType targetTable = database.EntityTypes.Select(t => new
                {
                    t = t,
                    n = t.GetTableName()
                }).Where(_param1 =>
                {
                    if (_param1.n != null)
                    {
                        return(_param1.n.Equals(this._tableName));
                    }
                    return(false);
                }).Select(_param0 => _param0.t).SingleOrDefault <EntityType>() ?? database.GetEntitySets().Where <EntitySet>((Func <EntitySet, bool>)(es => string.Equals(es.Table, this._tableName.Name, StringComparison.Ordinal))).Select <EntitySet, EntityType>((Func <EntitySet, EntityType>)(es => es.ElementType)).SingleOrDefault <EntityType>();
                if (targetTable == null)
                {
                    throw Error.TableNotFound((object)this._tableName);
                }
                EntityType sourceTable = associationSetMapping.Table;
                if (sourceTable != targetTable)
                {
                    ForeignKeyBuilder foreignKeyBuilder = sourceTable.ForeignKeyBuilders.Single <ForeignKeyBuilder>((Func <ForeignKeyBuilder, bool>)(fk => fk.DependentColumns.SequenceEqual <EdmProperty>(propertyMappings.Select <ScalarPropertyMapping, EdmProperty>((Func <ScalarPropertyMapping, EdmProperty>)(pm => pm.Column)))));
                    sourceTable.RemoveForeignKey(foreignKeyBuilder);
                    targetTable.AddForeignKey(foreignKeyBuilder);
                    foreignKeyBuilder.DependentColumns.Each <EdmProperty>((Action <EdmProperty>)(c =>
                    {
                        bool primaryKeyColumn = c.IsPrimaryKeyColumn;
                        sourceTable.RemoveMember((EdmMember)c);
                        targetTable.AddMember((EdmMember)c);
                        if (!primaryKeyColumn)
                        {
                            return;
                        }
                        targetTable.AddKeyMember((EdmMember)c);
                    }));
                    associationSetMapping.StoreEntitySet = database.GetEntitySet(targetTable);
                }
            }
            if (this._keyColumnNames.Count > 0 && this._keyColumnNames.Count != propertyMappings.Count <ScalarPropertyMapping>())
            {
                throw Error.IncorrectColumnCount((object)string.Join(", ", (IEnumerable <string>) this._keyColumnNames));
            }
            this._keyColumnNames.Each <string>((Action <string, int>)((n, i) => propertyMappings[i].Column.Name = n));
            foreach (KeyValuePair <Tuple <string, string>, object> annotation in (IEnumerable <KeyValuePair <Tuple <string, string>, object> >) this._annotations)
            {
                int index = this._keyColumnNames.IndexOf(annotation.Key.Item1);
                if (index == -1)
                {
                    throw new InvalidOperationException(Strings.BadKeyNameForAnnotation((object)annotation.Key.Item1, (object)annotation.Key.Item2));
                }
                propertyMappings[index].Column.AddAnnotation("http://schemas.microsoft.com/ado/2013/11/edm/customannotation:" + annotation.Key.Item2, annotation.Value);
            }
        }
Example #15
0
        public void Configure_should_throw_when_incorrect_number_of_columns_configured()
        {
            var database = new EdmModel(DataSpace.CSpace);

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

            var manyToManyAssociationMappingConfiguration
                = new ManyToManyAssociationMappingConfiguration();

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

            var mockPropertyInfo = new MockPropertyInfo();

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

            Assert.Equal(
                Strings.IncorrectColumnCount("Id1, Id2"),
                Assert.Throws <InvalidOperationException>(
                    () => manyToManyAssociationMappingConfiguration.Configure(associationSetMapping, database, mockPropertyInfo)).Message);
        }
 internal AssociationSetTranslator(AssociationSetMapping setMapping)
 {
     if (null != setMapping)
     {
         m_mapping = setMapping.ModificationFunctionMapping;
     }
 }
Example #17
0
        internal static void AddRule(CommandProcessorContext cpc, AssociationSetMapping associationSetMapping)
        {
            Debug.Assert(associationSetMapping != null, "associationSetMapping should not be null");

            IIntegrityCheck check = new EnforceAssociationSetMappingRules(cpc, associationSetMapping);

            cpc.AddIntegrityCheck(check);
        }
 internal AssociationSetTranslator(AssociationSetMapping setMapping)
 {
     if (setMapping == null)
     {
         return;
     }
     this.m_mapping = setMapping.ModificationFunctionMapping;
 }
        public void Initialize_should_initialize_ends()
        {
            var associationSetMapping
                = new AssociationSetMapping(new AssociationSet("AS", new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace)), new EntitySet()).Initialize();

            Assert.NotNull(associationSetMapping.SourceEndMapping);
            Assert.NotNull(associationSetMapping.TargetEndMapping);
        }
        public void Can_get_and_set_configuration_annotation()
        {
            var associationSetMapping
                = new AssociationSetMapping(new AssociationSet("AS", new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace)), new EntitySet());

            associationSetMapping.SetConfiguration(42);

            Assert.Equal(42, associationSetMapping.GetConfiguration());
        }
 private CreateEndScalarPropertyCommand(
     AssociationSetMapping associationSetMapping, AssociationSetEnd associationSetEnd, Property entityProperty, Property tableColumn,
     bool enforceConstraints)
 {
     Initialize(entityProperty, tableColumn, enforceConstraints);
     CommandValidation.ValidateAssociationSetMapping(associationSetMapping);
     CommandValidation.ValidateAssociationSetEnd(associationSetEnd);
     _associationSetMapping = associationSetMapping;
     _associationSetEnd     = associationSetEnd;
 }
Example #22
0
        public void Generate(
            AssociationSetMapping associationSetMapping,
            DbDatabaseMapping databaseMapping)
        {
            List <Tuple <ModificationFunctionMemberPath, EdmProperty> > list = ModificationFunctionMappingGenerator.GetIndependentFkColumns(associationSetMapping).ToList <Tuple <ModificationFunctionMemberPath, EdmProperty> >();
            string functionNamePrefix = associationSetMapping.AssociationSet.ElementType.SourceEnd.GetEntityType().Name + associationSetMapping.AssociationSet.ElementType.TargetEnd.GetEntityType().Name;
            ModificationFunctionMapping functionMapping1 = this.GenerateFunctionMapping(ModificationOperator.Insert, (EntitySetBase)associationSetMapping.AssociationSet, (EntityTypeBase)associationSetMapping.AssociationSet.ElementType, databaseMapping, Enumerable.Empty <EdmProperty>(), (IEnumerable <Tuple <ModificationFunctionMemberPath, EdmProperty> >)list, (IList <ColumnMappingBuilder>) new ColumnMappingBuilder[0], (IEnumerable <EdmProperty>)null, functionNamePrefix);
            ModificationFunctionMapping functionMapping2 = this.GenerateFunctionMapping(ModificationOperator.Delete, (EntitySetBase)associationSetMapping.AssociationSet, (EntityTypeBase)associationSetMapping.AssociationSet.ElementType, databaseMapping, Enumerable.Empty <EdmProperty>(), (IEnumerable <Tuple <ModificationFunctionMemberPath, EdmProperty> >)list, (IList <ColumnMappingBuilder>) new ColumnMappingBuilder[0], (IEnumerable <EdmProperty>)null, functionNamePrefix);

            associationSetMapping.ModificationFunctionMapping = new AssociationSetModificationFunctionMapping(associationSetMapping.AssociationSet, functionMapping2, functionMapping1);
        }
        /// <summary>
        ///     Creates a Condition in the given AssociationSetMapping.
        ///     Valid combinations are:
        ///     1. Send true or false for isNull, and null for conditionValue
        ///     2. Send null for isNull, and a non-empty string for conditionValue
        ///     3. Send null for isNull, and null for conditionValue
        ///     You cannot send non-null values to both arguments.
        /// </summary>
        /// <param name="mappingFragment">The AssociationSetMapping to place this Condition; cannot be null.</param>
        /// <param name="tableColumn">This must be a valid Property from the S-Model.</param>
        internal CreateEndConditionCommand(
            AssociationSetMapping associationSetMapping, Property tableColumn, bool?isNull, string conditionValue)
        {
            CommandValidation.ValidateAssociationSetMapping(associationSetMapping);
            CommandValidation.ValidateTableColumn(tableColumn);

            _associationSetMapping = associationSetMapping;
            _tableColumn           = tableColumn;
            _isNull         = isNull;
            _conditionValue = conditionValue;
        }
Example #24
0
        public static AssociationSetMapping AddAssociationSetMapping(
            this DbDatabaseMapping databaseMapping,
            AssociationSet associationSet,
            EntitySet entitySet)
        {
            EntityContainerMapping containerMapping = databaseMapping.EntityContainerMappings.Single <EntityContainerMapping>();
            AssociationSetMapping  setMapping       = new AssociationSetMapping(associationSet, entitySet, containerMapping).Initialize();

            containerMapping.AddSetMapping(setMapping);
            return(setMapping);
        }
Example #25
0
        private void GenerateManyToManyAssociation(
            AssociationType associationType,
            DbDatabaseMapping databaseMapping)
        {
            EntityType            entityType1           = associationType.SourceEnd.GetEntityType();
            EntityType            entityType2           = associationType.TargetEnd.GetEntityType();
            EntityType            dependentTable        = databaseMapping.Database.AddTable(entityType1.Name + entityType2.Name);
            AssociationSetMapping associationSetMapping = AssociationTypeMappingGenerator.GenerateAssociationSetMapping(associationType, databaseMapping, associationType.SourceEnd, associationType.TargetEnd, dependentTable);

            this.GenerateIndependentForeignKeyConstraint(databaseMapping, entityType1, entityType2, dependentTable, associationSetMapping, associationSetMapping.SourceEndMapping, associationType.SourceEnd.Name, (AssociationEndMember)null, true);
            this.GenerateIndependentForeignKeyConstraint(databaseMapping, entityType2, entityType1, dependentTable, associationSetMapping, associationSetMapping.TargetEndMapping, associationType.TargetEnd.Name, (AssociationEndMember)null, true);
        }
Example #26
0
        protected override void InvokeInternal(CommandProcessorContext cpc)
        {
            var end = new EndProperty(AssociationSetMapping, null);

            end.Name.SetRefName(AssociationSetEnd);
            AssociationSetMapping.AddEndProperty(end);

            XmlModelHelper.NormalizeAndResolve(end);

            Debug.Assert(end.Name.Target != null, "Could not resolve AssociationSetEnd in an EndProperty");
            _created = end;
        }
Example #27
0
        private static AssociationSetMapping GenerateAssociationSetMapping(
            AssociationType associationType,
            DbDatabaseMapping databaseMapping,
            AssociationEndMember principalEnd,
            AssociationEndMember dependentEnd,
            EntityType dependentTable)
        {
            AssociationSetMapping associationSetMapping = databaseMapping.AddAssociationSetMapping(databaseMapping.Model.GetAssociationSet(associationType), databaseMapping.Database.GetEntitySet(dependentTable));

            associationSetMapping.StoreEntitySet = databaseMapping.Database.GetEntitySet(dependentTable);
            associationSetMapping.SourceEndMapping.AssociationEnd = principalEnd;
            associationSetMapping.TargetEndMapping.AssociationEnd = dependentEnd;
            return(associationSetMapping);
        }
Example #28
0
        private void GenerateIndependentForeignKeyConstraint(
            DbDatabaseMapping databaseMapping,
            EntityType principalEntityType,
            EntityType dependentEntityType,
            EntityType dependentTable,
            AssociationSetMapping associationSetMapping,
            EndPropertyMapping associationEndMapping,
            string name,
            AssociationEndMember principalEnd,
            bool isPrimaryKeyColumn = false)
        {
            DebugCheck.NotNull(databaseMapping);
            DebugCheck.NotNull(principalEntityType);
            DebugCheck.NotNull(dependentTable);
            DebugCheck.NotNull(associationEndMapping);
            DebugCheck.NotEmpty(name);

            var principalTable
                = GetEntityTypeMappingInHierarchy(databaseMapping, principalEntityType)
                  .MappingFragments
                  .Single()
                  .Table;

            var foreignKeyConstraint
                = new ForeignKeyBuilder(databaseMapping.Database, name)
                {
                PrincipalTable = principalTable,
                DeleteAction   = associationEndMapping.AssociationEnd.DeleteBehavior != OperationAction.None
                                           ? associationEndMapping.AssociationEnd.DeleteBehavior
                                           : OperationAction.None
                };

            var principalNavigationProperty
                = databaseMapping.Model.EntityTypes
                  .SelectMany(e => e.DeclaredNavigationProperties)
                  .SingleOrDefault(n => n.ResultEnd == principalEnd);

            dependentTable.AddForeignKey(foreignKeyConstraint);

            foreignKeyConstraint.DependentColumns = GenerateIndependentForeignKeyColumns(
                principalEntityType,
                dependentEntityType,
                associationSetMapping,
                associationEndMapping,
                dependentTable,
                isPrimaryKeyColumn,
                principalNavigationProperty);
        }
Example #29
0
        private IEnumerable <EdmProperty> GenerateIndependentForeignKeyColumns(
            EntityType principalEntityType,
            EntityType dependentEntityType,
            AssociationSetMapping associationSetMapping,
            EndPropertyMapping associationEndMapping,
            EntityType dependentTable,
            bool isPrimaryKeyColumn,
            NavigationProperty principalNavigationProperty)
        {
            DebugCheck.NotNull(principalEntityType);
            DebugCheck.NotNull(associationEndMapping);
            DebugCheck.NotNull(dependentTable);

            foreach (var property in principalEntityType.KeyProperties())
            {
                var columnName
                    = ((principalNavigationProperty != null)
                           ? principalNavigationProperty.Name
                           : principalEntityType.Name) + "_" + property.Name;

                var foreignKeyColumn
                    = MapTableColumn(property, columnName, false);

                dependentTable.AddColumn(foreignKeyColumn);

                if (isPrimaryKeyColumn)
                {
                    dependentTable.AddKeyMember(foreignKeyColumn);
                }

                foreignKeyColumn.Nullable
                    = associationEndMapping.AssociationEnd.IsOptional() ||
                      (associationEndMapping.AssociationEnd.IsRequired() &&
                       dependentEntityType.BaseType != null);

                foreignKeyColumn.StoreGeneratedPattern = StoreGeneratedPattern.None;

                yield return(foreignKeyColumn);

                associationEndMapping.AddPropertyMapping(new ScalarPropertyMapping(property, foreignKeyColumn));

                if (foreignKeyColumn.Nullable)
                {
                    associationSetMapping
                    .AddCondition(new IsNullConditionMapping(foreignKeyColumn, false));
                }
            }
        }
        private static EndPropertyMapping GetForeignKeyEndMapFromAssocitionMap(
            AssociationSetMapping colocatedAssociationSetMap)
        {
            MappingFragment         mappingFragment = colocatedAssociationSetMap.TypeMappings.First <TypeMapping>().MappingFragments.First <MappingFragment>();
            IEnumerable <EdmMember> keyMembers      = (IEnumerable <EdmMember>)colocatedAssociationSetMap.StoreEntitySet.ElementType.KeyMembers;

            foreach (EndPropertyMapping propertyMapping in mappingFragment.PropertyMappings)
            {
                EndPropertyMapping endMap = propertyMapping;
                if (endMap.StoreProperties.SequenceEqual <EdmMember>(keyMembers, (IEqualityComparer <EdmMember>)System.Collections.Generic.EqualityComparer <EdmMember> .Default))
                {
                    return(mappingFragment.PropertyMappings.OfType <EndPropertyMapping>().Where <EndPropertyMapping>((Func <EndPropertyMapping, bool>)(eMap => !eMap.Equals((object)endMap))).First <EndPropertyMapping>());
                }
            }
            return((EndPropertyMapping)null);
        }
 internal AssociationSetTranslator(AssociationSetMapping setMapping)
 {
     if (null != setMapping)
     {
         m_mapping = setMapping.ModificationFunctionMapping;
     }
 }
 // <summary>
 // Initialize a translator for the given association set mapping.
 // </summary>
 // <param name="setMapping"> Association set mapping. </param>
 // <returns> Translator. </returns>
 internal static ModificationFunctionMappingTranslator CreateAssociationSetTranslator(
     AssociationSetMapping setMapping)
 {
     return new AssociationSetTranslator(setMapping);
 }