public void Apply_should_not_add_index_when_one_present()
        {
            var associationType
                = new AssociationType("A", "N", false, DataSpace.SSpace)
                {
                    Constraint
                        = new ReferentialConstraint(
                            new AssociationEndMember("F", new EntityType("P", "N", DataSpace.SSpace)),
                            new AssociationEndMember("T", new EntityType("D", "N", DataSpace.SSpace)),
                            new EdmProperty[] { },
                            new[] { new EdmProperty("A"), new EdmProperty("B") })
                };

            (new ForeignKeyIndexConvention()).Apply(associationType, null);

            var consolidatedIndexes
                = ConsolidatedIndex.BuildIndexes(
                    associationType.Name,
                    associationType.Constraint.ToProperties.Select(p => Tuple.Create(p.Name, p)));

            Assert.Equal(1, consolidatedIndexes.Count());

            (new ForeignKeyIndexConvention()).Apply(associationType, null);

            consolidatedIndexes
                = ConsolidatedIndex.BuildIndexes(
                    associationType.Name,
                    associationType.Constraint.ToProperties.Select(p => Tuple.Create(p.Name, p)));

            Assert.Equal(1, consolidatedIndexes.Count());
        }
        public static void Create_sets_properties_and_seals_the_instance()
        {
            var typeUsage = TypeUsage.CreateDefaultTypeUsage(PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String));
            var associationType = new AssociationType("AssociationType", "Namespace", true, DataSpace.CSpace);
            var source = new EntityType("Source", "Namespace", DataSpace.CSpace);
            var target = new EntityType("Target", "Namespace", DataSpace.CSpace);
            var sourceEnd = new AssociationEndMember("SourceEnd", source);
            var targetEnd = new AssociationEndMember("TargetEnd", target);            

            var navigationProperty =
                NavigationProperty.Create(
                    "NavigationProperty",
                    typeUsage,
                    associationType,
                    sourceEnd,
                    targetEnd,
                    new[]
                        {
                            new MetadataProperty(
                                "TestProperty",
                                TypeUsage.CreateDefaultTypeUsage(PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String)),
                                "value"),
                        });

            Assert.Equal("NavigationProperty", navigationProperty.Name);
            Assert.Same(typeUsage, navigationProperty.TypeUsage);
            Assert.Same(associationType, navigationProperty.RelationshipType);
            Assert.Same(sourceEnd, navigationProperty.FromEndMember);
            Assert.Same(targetEnd, navigationProperty.ToEndMember);
            Assert.True(navigationProperty.IsReadOnly);

            var metadataProperty = navigationProperty.MetadataProperties.SingleOrDefault(p => p.Name == "TestProperty");
            Assert.NotNull(metadataProperty);
            Assert.Equal("value", metadataProperty.Value);
        }
        public void Apply_should_discover_for_self_reference()
        {
            var associationType = new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace);
            associationType.SourceEnd = new AssociationEndMember("S", new EntityType("E", "N", DataSpace.CSpace));
            associationType.TargetEnd = new AssociationEndMember("T", associationType.SourceEnd.GetEntityType());

            associationType.SourceEnd.RelationshipMultiplicity = RelationshipMultiplicity.ZeroOrOne;

            associationType.TargetEnd.RelationshipMultiplicity = RelationshipMultiplicity.Many;

            var pkProperty = EdmProperty.Primitive("Id", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String));
            associationType.SourceEnd.GetEntityType().AddKeyMember(pkProperty);

            var fkProperty = EdmProperty.Primitive("NavId", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String));
            associationType.TargetEnd.GetEntityType().AddMember(fkProperty);
            associationType.TargetEnd.GetEntityType().AddNavigationProperty("Nav", associationType).ToEndMember = associationType.SourceEnd;
            associationType.TargetEnd.GetEntityType().AddNavigationProperty("Foos", associationType);

            // Foo.Id == Foo.NavId

            ((IEdmConvention<AssociationType>)new NavigationPropertyNameForeignKeyDiscoveryConvention())
                .Apply(associationType, new EdmModel(DataSpace.CSpace));

            Assert.NotNull(associationType.Constraint);
            Assert.Same(associationType.TargetEnd, associationType.Constraint.ToRole);
            Assert.Equal("NavId", associationType.Constraint.ToProperties.Single().Name);
        }
        public void Apply_is_noop_when_existing_constraint()
        {
            var associationType = new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace);
            associationType.SourceEnd = new AssociationEndMember("S", new EntityType("E", "N", DataSpace.CSpace));
            associationType.TargetEnd = new AssociationEndMember("T", new EntityType("E", "N", DataSpace.CSpace));

            var property = EdmProperty.Primitive("Fk", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String));

            var associationConstraint
                = new ReferentialConstraint(
                    associationType.SourceEnd,
                    associationType.TargetEnd,
                    new[] { property },
                    new[] { property });

            associationType.Constraint = associationConstraint;

            var navigationProperty = new NavigationProperty("N", TypeUsage.Create(new EntityType("E", "N", DataSpace.CSpace)))
                                         {
                                             RelationshipType = associationType
                                         };

            ((IEdmConvention<NavigationProperty>)new ForeignKeyNavigationPropertyAttributeConvention())
                .Apply(navigationProperty, new EdmModel(DataSpace.CSpace));

            Assert.Same(associationConstraint, navigationProperty.Association.Constraint);
        }
        public void Can_get_and_set_ends_via_wrapper_properties()
        {
            var associationType
                = new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace)
                      {
                          SourceEnd = new AssociationEndMember("S", new EntityType("E", "N", DataSpace.CSpace)),
                          TargetEnd = new AssociationEndMember("T", new EntityType("E", "N", DataSpace.CSpace))
                      };

            var associationSet = new AssociationSet("A", associationType);

            Assert.Null(associationSet.SourceSet);
            Assert.Null(associationSet.TargetSet);

            var sourceEntitySet = new EntitySet();

            associationSet.SourceSet = sourceEntitySet;

            var targetEntitySet = new EntitySet();

            associationSet.TargetSet = targetEntitySet;

            Assert.Same(sourceEntitySet, associationSet.SourceSet);
            Assert.Same(targetEntitySet, associationSet.TargetSet);
        }
        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 void Configure_should_configure_inverse()
        {
            var inverseMockPropertyInfo = new MockPropertyInfo();
            var navigationPropertyConfiguration = new NavigationPropertyConfiguration(new MockPropertyInfo())
                                                      {
                                                          InverseNavigationProperty = inverseMockPropertyInfo
                                                      };
            var associationType = new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace);
            associationType.SourceEnd = new AssociationEndMember("S", new EntityType("E", "N", DataSpace.CSpace));
            associationType.TargetEnd = new AssociationEndMember("T", new EntityType("E", "N", DataSpace.CSpace));
            var inverseAssociationType = new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace);
            inverseAssociationType.SourceEnd = new AssociationEndMember("S", new EntityType("E", "N", DataSpace.CSpace));
            inverseAssociationType.TargetEnd = new AssociationEndMember("T", new EntityType("E", "N", DataSpace.CSpace));
            var model = new EdmModel(DataSpace.CSpace);
            model.AddAssociationType(inverseAssociationType);
            var inverseNavigationProperty
                = model.AddEntityType("T")
                       .AddNavigationProperty("N", inverseAssociationType);
            inverseNavigationProperty.SetClrPropertyInfo(inverseMockPropertyInfo);

            navigationPropertyConfiguration.Configure(
                new NavigationProperty("N", TypeUsage.Create(associationType.TargetEnd.GetEntityType()))
                    {
                        RelationshipType = associationType
                    }, model, new EntityTypeConfiguration(typeof(object)));

            Assert.Same(associationType, inverseNavigationProperty.Association);
            Assert.Same(associationType.SourceEnd, inverseNavigationProperty.ResultEnd);
            Assert.Same(associationType.TargetEnd, inverseNavigationProperty.FromEndMember);
            Assert.Equal(0, model.AssociationTypes.Count());
        }
        /// <inheritdoc/>
        protected override bool MatchDependentKeyProperty(
            AssociationType associationType,
            AssociationEndMember dependentAssociationEnd,
            EdmProperty dependentProperty,
            EntityType principalEntityType,
            EdmProperty principalKeyProperty)
        {
            Check.NotNull(associationType, "associationType");
            Check.NotNull(dependentAssociationEnd, "dependentAssociationEnd");
            Check.NotNull(dependentProperty, "dependentProperty");
            Check.NotNull(principalEntityType, "principalEntityType");
            Check.NotNull(principalKeyProperty, "principalKeyProperty");

            var otherEnd = associationType.GetOtherEnd(dependentAssociationEnd);

            var navigationProperty
                = dependentAssociationEnd.GetEntityType().NavigationProperties
                                         .SingleOrDefault(n => n.ResultEnd == otherEnd);

            if (navigationProperty == null)
            {
                return false;
            }

            return string.Equals(
                dependentProperty.Name, navigationProperty.Name + principalKeyProperty.Name,
                StringComparison.OrdinalIgnoreCase);
        }
        // <summary>
        // Add the rel property induced by the specified relationship, (if the target
        // end has a multiplicity of one)
        // We only keep track of rel-properties that are "interesting"
        // </summary>
        // <param name="associationType"> the association relationship </param>
        // <param name="fromEnd"> source end of the relationship traversal </param>
        // <param name="toEnd"> target end of the traversal </param>
        private void AddRelProperty(
            AssociationType associationType,
            AssociationEndMember fromEnd, AssociationEndMember toEnd)
        {
            if (toEnd.RelationshipMultiplicity
                == RelationshipMultiplicity.Many)
            {
                return;
            }
            var prop = new RelProperty(associationType, fromEnd, toEnd);
            if (_interestingRelProperties == null
                ||
                !_interestingRelProperties.Contains(prop))
            {
                return;
            }

            var entityType = ((RefType)fromEnd.TypeUsage.EdmType).ElementType;
            List<RelProperty> propList;
            if (!_relPropertyMap.TryGetValue(entityType, out propList))
            {
                propList = new List<RelProperty>();
                _relPropertyMap[entityType] = propList;
            }
            propList.Add(prop);
        }
        public void HasCascadeDeletePath_should_return_true_for_transitive_cascade()
        {
            var model = new EdmModel(DataSpace.CSpace);
            var entityTypeA = model.AddEntityType("A");
            var entityTypeB = model.AddEntityType("B");
            var entityTypeC = model.AddEntityType("B");
            var associationTypeA
                = new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace)
                      {
                          SourceEnd = new AssociationEndMember("S", entityTypeA),
                          TargetEnd = new AssociationEndMember("T", entityTypeB)
                      };

            associationTypeA.SourceEnd.DeleteBehavior = OperationAction.Cascade;
            model.AddAssociationType(associationTypeA);
            var associationTypeB
                = new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace)
                      {
                          SourceEnd = new AssociationEndMember("S", entityTypeB),
                          TargetEnd = new AssociationEndMember("T", entityTypeC)
                      };

            associationTypeB.SourceEnd.DeleteBehavior = OperationAction.Cascade;
            model.AddAssociationType(associationTypeB);

            Assert.True(model.HasCascadeDeletePath(entityTypeA, entityTypeB));
            Assert.True(model.HasCascadeDeletePath(entityTypeB, entityTypeC));
            Assert.True(model.HasCascadeDeletePath(entityTypeA, entityTypeC));
            Assert.False(model.HasCascadeDeletePath(entityTypeB, entityTypeA));
            Assert.False(model.HasCascadeDeletePath(entityTypeC, entityTypeB));
            Assert.False(model.HasCascadeDeletePath(entityTypeC, entityTypeA));
        }
        public void Can_get_and_set_constraint_via_wrapper_property()
        {
            var associationType
                = new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace)
                      {
                          SourceEnd = new AssociationEndMember("S", new EntityType("E", "N", DataSpace.CSpace)),
                          TargetEnd = new AssociationEndMember("T", new EntityType("E", "N", DataSpace.CSpace))
                      };

            Assert.Null(associationType.Constraint);
            Assert.False(associationType.IsForeignKey);

            var property
                = EdmProperty.CreatePrimitive("Fk", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String));

            var referentialConstraint
                = new ReferentialConstraint(
                    associationType.SourceEnd,
                    associationType.TargetEnd,
                    new[] { property },
                    new[] { property });

            associationType.Constraint = referentialConstraint;

            Assert.Same(referentialConstraint, associationType.Constraint);
            Assert.True(associationType.IsForeignKey);
        }
        public void Apply_should_set_principal_end_kind_to_required_when_all_properties_not_nullable()
        {
            var associationType = new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace);
            associationType.SourceEnd = new AssociationEndMember("S", new EntityType("E", "N", DataSpace.CSpace));
            associationType.TargetEnd = new AssociationEndMember("T", new EntityType("E", "N", DataSpace.CSpace));

            associationType.SourceEnd.RelationshipMultiplicity = RelationshipMultiplicity.ZeroOrOne;

            var property1 = EdmProperty.CreatePrimitive("P1", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String));
            var property2 = EdmProperty.CreatePrimitive("P2", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String));

            var associationConstraint
                = new ReferentialConstraint(
                    associationType.SourceEnd,
                    associationType.TargetEnd,
                    new[]
                        {
                            property1,
                            property2
                        },
                    new[]
                        {
                            property1,
                            property2
                        });

            associationConstraint.ToProperties.Each(p => p.Nullable = false);

            associationType.Constraint = associationConstraint;

            (new ForeignKeyAssociationMultiplicityConvention())
                .Apply(associationType, new DbModel(new EdmModel(DataSpace.CSpace), null));

            Assert.True(associationType.SourceEnd.IsRequired());
        }
        public static void SetAssociationType(
            this ForeignKeyBuilder fk, AssociationType associationType)
        {
            DebugCheck.NotNull(fk);
            DebugCheck.NotNull(associationType);

            fk.Annotations.SetAnnotation(AssociationType, associationType);
        }
        public static void SetAssociationType(
            this ForeignKeyBuilder fk, AssociationType associationType)
        {
            DebugCheck.NotNull(fk);
            DebugCheck.NotNull(associationType);

            fk.GetMetadataProperties().SetAnnotation(AssociationType, associationType);
        }
        public void Can_get_and_set_configuration_facet()
        {
            var associationType = new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace);
            associationType.SourceEnd = new AssociationEndMember("S", new EntityType("E", "N", DataSpace.CSpace));
            associationType.TargetEnd = new AssociationEndMember("T", new EntityType("E", "N", DataSpace.CSpace));
            associationType.SetConfiguration(42);

            Assert.Equal(42, associationType.GetConfiguration());
        }
        public void Initialize_should_create_association_ends()
        {
            var associationType = new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace);
            associationType.SourceEnd = new AssociationEndMember("S", new EntityType("E", "N", DataSpace.CSpace));
            associationType.TargetEnd = new AssociationEndMember("T", new EntityType("E", "N", DataSpace.CSpace));

            Assert.NotNull(associationType.SourceEnd);
            Assert.NotNull(associationType.TargetEnd);
        }
        public void GetOtherEnd_should_return_correct_end()
        {
            var associationType = new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace);
            associationType.SourceEnd = new AssociationEndMember("S", new EntityType("E", "N", DataSpace.CSpace));
            associationType.TargetEnd = new AssociationEndMember("T", new EntityType("E", "N", DataSpace.CSpace));

            Assert.Same(associationType.SourceEnd, associationType.GetOtherEnd(associationType.TargetEnd));
            Assert.Same(associationType.TargetEnd, associationType.GetOtherEnd(associationType.SourceEnd));
        }
        internal override void Configure(
            AssociationType associationType, AssociationEndMember dependentEnd,
            EntityTypeConfiguration entityTypeConfiguration)
        {
            DebugCheck.NotNull(associationType);
            DebugCheck.NotNull(dependentEnd);
            DebugCheck.NotNull(entityTypeConfiguration);

            associationType.MarkIndependent();
        }
        public void IsManyToMany_should_be_true_when_source_many_and_target_many()
        {
            var associationType = new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace);
            associationType.SourceEnd = new AssociationEndMember("S", new EntityType("E", "N", DataSpace.CSpace));
            associationType.TargetEnd = new AssociationEndMember("T", new EntityType("E", "N", DataSpace.CSpace));
            associationType.SourceEnd.RelationshipMultiplicity = RelationshipMultiplicity.Many;
            associationType.TargetEnd.RelationshipMultiplicity = RelationshipMultiplicity.Many;

            Assert.True(associationType.IsManyToMany());
        }
        public void Can_mark_association_as_independent()
        {
            var associationType = new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace);

            Assert.False(associationType.IsIndependent());

            associationType.MarkIndependent();

            Assert.True(associationType.IsIndependent());
        }
        public void Can_get_association_set_mapping()
        {
            var associationType = new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace);
            var associationSetMapping
                = new AssociationSetMapping(
                    new AssociationSet("AS", associationType), 
                    new EntityContainerMapping(new EntityContainer("C", DataSpace.CSpace)));
            var associationTypeMapping = new AssociationTypeMapping(associationSetMapping);

            Assert.Same(associationSetMapping, associationTypeMapping.AssociationSetMapping);
        }
        public void Cannot_create_with_null_argument()
        {
            var associationType = new AssociationType("AT", "N", false, DataSpace.CSpace);
            var associationSet = new AssociationSet("AS", associationType);

            Assert.Equal(
                "members",
                Assert.Throws<ArgumentNullException>(
                    () => new ModificationFunctionMemberPath(
                        null, associationSet)).ParamName);
        }
        public void IsOfType_collection_empty()
        {
            var associationType = new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace);

            var setMapping
                = new StorageEntitySetMapping(
                    new EntitySet(),
                    new StorageEntityContainerMapping(new EntityContainer("C", DataSpace.CSpace)));

            Assert.Empty(new StorageAssociationTypeMapping(associationType, setMapping).IsOfTypes);
        }
        public void Apply_should_not_discover_when_independent_constraint()
        {
            var associationType = new AssociationType();
            associationType.SourceEnd = new AssociationEndMember("S", new EntityType());
            associationType.TargetEnd = new AssociationEndMember("T", new EntityType());
            associationType.MarkIndependent();

            ((IEdmConvention<AssociationType>)new TypeNameForeignKeyDiscoveryConvention())
                .Apply(associationType, new EdmModel().Initialize());

            Assert.Null(associationType.Constraint);
        }
 private static void FixNavigationProperties(
     EdmModel model, AssociationType unifiedAssociation, AssociationType redundantAssociation)
 {
     foreach (var navigationProperty
         in model.GetEntityTypes()
                 .SelectMany(e => e.NavigationProperties)
                 .Where(np => np.Association == redundantAssociation))
     {
         navigationProperty.RelationshipType = unifiedAssociation;
         navigationProperty.ToEndMember = unifiedAssociation.SourceEnd;
     }
 }
        public void Apply_should_not_add_action_when_self_reference()
        {
            var associationType = new AssociationType();
            associationType.SourceEnd = new AssociationEndMember("S", new EntityType());
            associationType.TargetEnd = new AssociationEndMember("T", associationType.SourceEnd.GetEntityType());

            ((IEdmConvention<AssociationType>)new OneToManyCascadeDeleteConvention())
                .Apply(associationType, new EdmModel().Initialize());

            Assert.Equal(OperationAction.None, associationType.SourceEnd.DeleteBehavior);
            Assert.Equal(OperationAction.None, associationType.TargetEnd.DeleteBehavior);
        }
        public void Apply_should_not_add_action_when_self_reference()
        {
            var associationType = new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace);
            associationType.SourceEnd = new AssociationEndMember("S", new EntityType("E", "N", DataSpace.CSpace));
            associationType.TargetEnd = new AssociationEndMember("T", associationType.SourceEnd.GetEntityType());

            ((IEdmConvention<AssociationType>)new OneToManyCascadeDeleteConvention())
                .Apply(associationType, new EdmModel(DataSpace.CSpace));

            Assert.Equal(OperationAction.None, associationType.SourceEnd.DeleteBehavior);
            Assert.Equal(OperationAction.None, associationType.TargetEnd.DeleteBehavior);
        }
        public void Apply_should_not_discover_when_independent_constraint()
        {
            var associationType = new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace);
            associationType.SourceEnd = new AssociationEndMember("S", new EntityType("E", "N", DataSpace.CSpace));
            associationType.TargetEnd = new AssociationEndMember("T", new EntityType("E", "N", DataSpace.CSpace));
            associationType.MarkIndependent();

            (new TypeNameForeignKeyDiscoveryConvention())
                .Apply(associationType, new DbModel(new EdmModel(DataSpace.CSpace), null));

            Assert.Null(associationType.Constraint);
        }
        public void Association_type_returned_in_type_collection()
        {
            var associationType = new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace);

            var setMapping
                = new StorageEntitySetMapping(
                    new EntitySet(),
                    new StorageEntityContainerMapping(new EntityContainer("C", DataSpace.CSpace)));

            Assert.Same(
                associationType,
                new StorageAssociationTypeMapping(associationType, setMapping).Types.Single());
        }
        public void Can_get_association_type()
        {
            var associationType = new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace);

            var setMapping
                = new StorageEntitySetMapping(
                    new EntitySet(),
                    new StorageEntityContainerMapping(new EntityContainer("C", DataSpace.CSpace)));

            Assert.Same(
                associationType,
                new StorageAssociationTypeMapping(associationType, setMapping).AssociationType);
        }
Esempio n. 31
0
        private void ResolveAssociationEnd(
            AssociationType associationType,
            string roleName,
            Type clrType,
            RelationshipMultiplicity multiplicity)
        {
            EntityType entityType;

            if (!this.TryGetRelationshipEndEntityType(clrType, out entityType))
            {
                this.SessionData.EdmItemErrors.Add(new EdmItemError(Strings.RoleTypeInEdmRelationshipAttributeIsInvalidType((object)associationType.Name, (object)roleName, (object)clrType)));
            }
            else
            {
                associationType.AddKeyMember((EdmMember) new AssociationEndMember(roleName, entityType.GetReferenceType(), multiplicity));
            }
        }
Esempio n. 32
0
        public void Can_get_and_set_ends_via_wrapper_properties()
        {
            var associationType = new AssociationType();

            Assert.Null(associationType.SourceEnd);
            Assert.Null(associationType.TargetEnd);

            var sourceEnd = new AssociationEndMember("S", new EntityType());

            associationType.SourceEnd = sourceEnd;

            var targetEnd = new AssociationEndMember("T", new EntityType());

            associationType.TargetEnd = targetEnd;

            Assert.Same(sourceEnd, associationType.SourceEnd);
            Assert.Same(targetEnd, associationType.TargetEnd);
        }
Esempio n. 33
0
        public void Can_get_and_set_ends_via_wrapper_properties()
        {
            var associationType = new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace);

            Assert.Null(associationType.SourceEnd);
            Assert.Null(associationType.TargetEnd);

            var sourceEnd = new AssociationEndMember("S", new EntityType("E", "N", DataSpace.CSpace));

            associationType.SourceEnd = sourceEnd;

            var targetEnd = new AssociationEndMember("T", new EntityType("E", "N", DataSpace.CSpace));

            associationType.TargetEnd = targetEnd;

            Assert.Same(sourceEnd, associationType.SourceEnd);
            Assert.Same(targetEnd, associationType.TargetEnd);
        }
        [Fact] // Codeplex 1735
        public void EdmAssociationType_ValidateReferentialConstraint_validates_composite_key_properties_in_correct_order()
        {
            var principal = new EntityType(
                "Principal", "N", DataSpace.CSpace,
                new[] { "IdInt", "IdString" },
                new EdmMember[]
            {
                new EdmProperty("IdInt", TypeUsage.Create(PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.Int32))),
                new EdmProperty("IdString", TypeUsage.Create(PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String)))
            });

            var dependent = new EntityType(
                "Dependent", "N", DataSpace.CSpace,
                new[] { "Id" },
                new EdmMember[]
            {
                new EdmProperty("Id", TypeUsage.Create(PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.Int32))),
                new EdmProperty("IdString", TypeUsage.Create(PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String))),
                new EdmProperty("IdInt", TypeUsage.Create(PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.Int32)))
            });

            var associationType = new AssociationType("AT", "N", true, DataSpace.CSpace);

            var fromRole = new AssociationEndMember("Principal", new RefType(principal), RelationshipMultiplicity.ZeroOrOne);
            var toRole   = new AssociationEndMember("Dependent", new RefType(dependent), RelationshipMultiplicity.Many);

            associationType.Constraint = new ReferentialConstraint(
                fromRole, toRole,
                new[] { principal.Properties["IdString"], principal.Properties["IdInt"] },
                new[] { dependent.Properties["IdString"], dependent.Properties["IdInt"] });

            var validationContext
                = new EdmModelValidationContext(new EdmModel(DataSpace.CSpace), true);

            DataModelErrorEventArgs errorEventArgs = null;

            validationContext.OnError += (_, e) => errorEventArgs = e;

            EdmModelSemanticValidationRules
            .EdmAssociationType_ValidateReferentialConstraint
            .Evaluate(validationContext, associationType);

            Assert.Null(errorEventArgs);
        }
        private DataModelErrorEventArgs ValidateAssociationTypeWithNonFkeyReference(DataSpace dataSpace)
        {
            var model = new EdmModel(dataSpace, 1.0);

            var intType =
                dataSpace == DataSpace.CSpace
                    ? PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.Int32)
                    : FakeSqlProviderServices.Instance.GetProviderManifest("2008").GetStoreTypes().Single(t => t.Name == "int");

            var principal =
                new EntityType("P", "ns", dataSpace, new [] { "Id" }, new[] { EdmProperty.CreatePrimitive("Id", intType) });
            var dependent =
                new EntityType("P", "ns", dataSpace, new [] { "Id" },
                               new[] { EdmProperty.CreatePrimitive("Id", intType), EdmProperty.CreatePrimitive("NonKeyProperty", intType) });

            foreach (var property in principal.Properties.Concat(dependent.Properties))
            {
                property.Nullable = false;
            }

            var associationType =
                new AssociationType("AT", "ns", false, dataSpace)
            {
                Constraint = new ReferentialConstraint(
                    new AssociationEndMember("P", principal.GetReferenceType(), RelationshipMultiplicity.One),
                    new AssociationEndMember("C", dependent.GetReferenceType(), RelationshipMultiplicity.Many),
                    principal.KeyProperties,
                    dependent.Properties.Where(p => p.Name == "NonKeyProperty"))
            };

            model.AddAssociationType(associationType);

            var validationContext = new EdmModelValidationContext(model, true);

            DataModelErrorEventArgs errorEventArgs = null;

            validationContext.OnError += (_, e) => errorEventArgs = e;

            EdmModelSemanticValidationRules
            .EdmAssociationType_ValidateReferentialConstraint
            .Evaluate(validationContext, model.AssociationTypes.Single());

            return(errorEventArgs);
        }
Esempio n. 36
0
        protected internal override void VisitEdmAssociationType(AssociationType item)
        {
            var builder = new StringBuilder();

            AppendSchemaErrors(builder, item);

            if (MetadataItemHelper.IsInvalid(item))
            {
                AppendMetadataItem(builder, item, (v, i) => v.InternalVisitEdmAssociationType(i));

                WriteComment(builder.ToString());
            }
            else
            {
                WriteComment(builder.ToString());

                InternalVisitEdmAssociationType(item);
            }
        }
        private static AssociationType CreateCSpaceAssociationType(int index)
        {
            var sourceProperty = new EdmProperty("SourceProperty");
            var targetProperty = new EdmProperty("TargetProperty");

            var sourceEntityType = EntityType.Create(
                "SourceEntityType" + index,
                "Namespace",
                DataSpace.CSpace,
                new [] { "SourceProperty" },
                new[] { sourceProperty },
                Enumerable.Empty <MetadataProperty>());
            var targetEntityType = EntityType.Create(
                "TargetEntityType" + index,
                "Namespace",
                DataSpace.CSpace,
                new[] { "TargetProperty" },
                new[] { targetProperty },
                Enumerable.Empty <MetadataProperty>());

            var sourceEnd = new AssociationEndMember("SourceEnd" + index, sourceEntityType);
            var targetEnd = new AssociationEndMember("TargetEnd" + index, targetEntityType);

            var constraint =
                new ReferentialConstraint(
                    sourceEnd,
                    targetEnd,
                    new[] { sourceProperty },
                    new[] { targetProperty });

            var associationType =
                AssociationType.Create(
                    "AssociationType" + index,
                    "Namespace",
                    true,
                    DataSpace.CSpace,
                    sourceEnd,
                    targetEnd,
                    constraint,
                    Enumerable.Empty <MetadataProperty>());

            return(associationType);
        }
        internal AssociationType GetOSpaceAssociationType(
            AssociationType cSpaceAssociationType,
            Func <AssociationType> initializer)
        {
            AssociationType[] associationTypes = this.GetOSpaceAssociationTypes();
            int index = cSpaceAssociationType.Index;

            Thread.MemoryBarrier();
            AssociationType associationType = associationTypes[index];

            if (associationType == null)
            {
                associationType         = initializer();
                associationType.Index   = index;
                associationTypes[index] = associationType;
                Thread.MemoryBarrier();
            }
            return(associationType);
        }
        private static NavigationProperty ConvertToNavigationProperty(
            EntityType declaringEntityType,
            System.Data.Entity.Core.SchemaObjectModel.NavigationProperty somNavigationProperty,
            DbProviderManifest providerManifest,
            Converter.ConversionCache convertedItemCache,
            Dictionary <SchemaElement, GlobalItem> newGlobalItems)
        {
            EntityType       endMemberType   = (EntityType)Converter.LoadSchemaElement(somNavigationProperty.Type, providerManifest, convertedItemCache, newGlobalItems);
            AssociationType  associationType = (AssociationType)Converter.LoadSchemaElement((System.Data.Entity.Core.SchemaObjectModel.SchemaType)somNavigationProperty.Relationship, providerManifest, convertedItemCache, newGlobalItems);
            IRelationshipEnd end             = (IRelationshipEnd)null;

            somNavigationProperty.Relationship.TryGetEnd(somNavigationProperty.ToEnd.Name, out end);
            RelationshipMultiplicity?multiplicity1 = end.Multiplicity;
            EdmType edmType = (multiplicity1.GetValueOrDefault() != RelationshipMultiplicity.Many ? 0 : (multiplicity1.HasValue ? 1 : 0)) == 0 ? (EdmType)endMemberType : (EdmType)endMemberType.GetCollectionType();
            RelationshipMultiplicity?multiplicity2 = end.Multiplicity;
            TypeUsage typeUsage;

            if ((multiplicity2.GetValueOrDefault() != RelationshipMultiplicity.One ? 0 : (multiplicity2.HasValue ? 1 : 0)) != 0)
            {
                typeUsage = TypeUsage.Create(edmType, new FacetValues()
                {
                    Nullable = (FacetValueContainer <bool?>) new bool?(false)
                });
            }
            else
            {
                typeUsage = TypeUsage.Create(edmType);
            }
            Converter.InitializeAssociationEndMember(associationType, somNavigationProperty.ToEnd, endMemberType);
            Converter.InitializeAssociationEndMember(associationType, somNavigationProperty.FromEnd, declaringEntityType);
            NavigationProperty navigationProperty = new NavigationProperty(somNavigationProperty.Name, typeUsage);

            navigationProperty.RelationshipType = (RelationshipType)associationType;
            navigationProperty.ToEndMember      = (RelationshipEndMember)associationType.Members[somNavigationProperty.ToEnd.Name];
            navigationProperty.FromEndMember    = (RelationshipEndMember)associationType.Members[somNavigationProperty.FromEnd.Name];
            if (somNavigationProperty.Documentation != null)
            {
                navigationProperty.Documentation = Converter.ConvertToDocumentation(somNavigationProperty.Documentation);
            }
            Converter.AddOtherContent((SchemaElement)somNavigationProperty, (MetadataItem)navigationProperty);
            return(navigationProperty);
        }
Esempio n. 40
0
 internal static AssociationEndMember GetEndThatShouldBeMappedToKey(
     AssociationType associationType)
 {
     if (associationType.AssociationEndMembers.Any <AssociationEndMember>((Func <AssociationEndMember, bool>)(it => it.RelationshipMultiplicity.Equals((object)RelationshipMultiplicity.One))))
     {
         return(associationType.AssociationEndMembers.SingleOrDefault <AssociationEndMember>((Func <AssociationEndMember, bool>)(it =>
         {
             if (!it.RelationshipMultiplicity.Equals((object)RelationshipMultiplicity.Many))
             {
                 return it.RelationshipMultiplicity.Equals((object)RelationshipMultiplicity.ZeroOrOne);
             }
             return true;
         })));
     }
     if (associationType.AssociationEndMembers.Any <AssociationEndMember>((Func <AssociationEndMember, bool>)(it => it.RelationshipMultiplicity.Equals((object)RelationshipMultiplicity.ZeroOrOne))))
     {
         return(associationType.AssociationEndMembers.SingleOrDefault <AssociationEndMember>((Func <AssociationEndMember, bool>)(it => it.RelationshipMultiplicity.Equals((object)RelationshipMultiplicity.Many))));
     }
     return((AssociationEndMember)null);
 }
        public void Can_add_association_set_to_container()
        {
            var entityContainer = new EntityContainer("Container", DataSpace.CSpace);
            var associationType
                = new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace)
                {
                SourceEnd = new AssociationEndMember("S", new EntityType("E", "N", DataSpace.CSpace)),
                TargetEnd = new AssociationEndMember("T", new EntityType("E", "N", DataSpace.CSpace))
                };
            var associationSet = new AssociationSet("A", associationType);

            Assert.Equal(0, entityContainer.EntitySets.Count);
            Assert.Null(associationSet.EntityContainer);

            entityContainer.AddEntitySetBase(associationSet);

            Assert.Equal(1, entityContainer.AssociationSets.Count);
            Assert.Same(associationSet, entityContainer.AssociationSets.Single());
            Assert.Same(entityContainer, associationSet.EntityContainer);
        }
        public IEnumerable <EdmProperty> GetDependentProperties()
        {
            AssociationType relationshipType = (AssociationType)this.RelationshipType;

            if (relationshipType.ReferentialConstraints.Count > 0)
            {
                ReferentialConstraint referentialConstraint = relationshipType.ReferentialConstraints[0];
                if (referentialConstraint.ToRole.EdmEquals((MetadataItem)this.FromEndMember))
                {
                    ReadOnlyMetadataCollection <EdmMember> keyMembers = referentialConstraint.FromRole.GetEntityType().KeyMembers;
                    List <EdmProperty> edmPropertyList = new List <EdmProperty>(keyMembers.Count);
                    for (int index = 0; index < keyMembers.Count; ++index)
                    {
                        edmPropertyList.Add(referentialConstraint.ToProperties[referentialConstraint.FromProperties.IndexOf((EdmProperty)keyMembers[index])]);
                    }
                    return((IEnumerable <EdmProperty>) new ReadOnlyCollection <EdmProperty>((IList <EdmProperty>)edmPropertyList));
                }
            }
            return(Enumerable.Empty <EdmProperty>());
        }
Esempio n. 43
0
        public virtual void CreateRelationships(EdmItemCollection edmItemCollection)
        {
            foreach (var cspaceAssociation in edmItemCollection.GetItems <AssociationType>())
            {
                Debug.Assert(cspaceAssociation.RelationshipEndMembers.Count == 2, "Relationships are assumed to have exactly two ends");

                if (CspaceToOspace.ContainsKey(cspaceAssociation))
                {
                    // don't try to load relationships that we already know about
                    continue;
                }

                var ospaceEndTypes = new EdmType[2];
                if (CspaceToOspace.TryGetValue(
                        GetRelationshipEndType(cspaceAssociation.RelationshipEndMembers[0]), out ospaceEndTypes[0]) &&
                    CspaceToOspace.TryGetValue(
                        GetRelationshipEndType(cspaceAssociation.RelationshipEndMembers[1]), out ospaceEndTypes[1]))
                {
                    Debug.Assert(ospaceEndTypes[0] is StructuralType);
                    Debug.Assert(ospaceEndTypes[1] is StructuralType);

                    // if we can find both ends of the relationship, then create it

                    var ospaceAssociation = new AssociationType(
                        cspaceAssociation.Name, cspaceAssociation.NamespaceName, cspaceAssociation.IsForeignKey, DataSpace.OSpace);
                    for (var i = 0; i < cspaceAssociation.RelationshipEndMembers.Count; i++)
                    {
                        var ospaceEndType = (EntityType)ospaceEndTypes[i];
                        var cspaceEnd     = cspaceAssociation.RelationshipEndMembers[i];

                        ospaceAssociation.AddKeyMember(
                            new AssociationEndMember(cspaceEnd.Name, ospaceEndType.GetReferenceType(), cspaceEnd.RelationshipMultiplicity));
                    }

                    AddToTypesInAssembly(ospaceAssociation);
                    LoadedTypes.Add(ospaceAssociation.FullName, ospaceAssociation);
                    CspaceToOspace.Add(cspaceAssociation, ospaceAssociation);
                }
            }
        }
        internal AssociationSet FindCSpaceAssociationSet(
            AssociationType associationType,
            string endName,
            string entitySetName,
            string entityContainerName,
            out EntitySet endEntitySet)
        {
            object associationTypeToSets = this.GetCSpaceAssociationTypeToSetsMap()[associationType.Index];

            if (associationTypeToSets == null)
            {
                endEntitySet = (EntitySet)null;
                return((AssociationSet)null);
            }
            AssociationSet associationSet1 = associationTypeToSets as AssociationSet;

            if (associationSet1 != null)
            {
                EntitySet entitySet = associationSet1.AssociationSetEnds[endName].EntitySet;
                if (entitySet.Name == entitySetName && entitySet.EntityContainer.Name == entityContainerName)
                {
                    endEntitySet = entitySet;
                    return(associationSet1);
                }
                endEntitySet = (EntitySet)null;
                return((AssociationSet)null);
            }
            foreach (AssociationSet associationSet2 in (AssociationSet[])associationTypeToSets)
            {
                EntitySet entitySet = associationSet2.AssociationSetEnds[endName].EntitySet;
                if (entitySet.Name == entitySetName && entitySet.EntityContainer.Name == entityContainerName)
                {
                    endEntitySet = entitySet;
                    return(associationSet2);
                }
            }
            endEntitySet = (EntitySet)null;
            return((AssociationSet)null);
        }
Esempio n. 45
0
        public static void Adding_a_NavigationProperty_to_an_EntityType_can_be_forced_when_read_only()
        {
            var typeUsage       = TypeUsage.CreateDefaultTypeUsage(PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String));
            var associationType = new AssociationType("AssociationType", "Namespace", true, DataSpace.CSpace);
            var source          = new EntityType("Source", "Namespace", DataSpace.CSpace);
            var target          = new EntityType("Target", "Namespace", DataSpace.CSpace);
            var sourceEnd       = new AssociationEndMember("SourceEnd", source);
            var targetEnd       = new AssociationEndMember("TargetEnd", target);

            var navigationProperty =
                NavigationProperty.Create(
                    "NavigationProperty",
                    typeUsage,
                    associationType,
                    sourceEnd,
                    targetEnd,
                    null);

            source.SetReadOnly();
            Assert.True(source.IsReadOnly);

            Assert.Equal(
                Resources.Strings.OperationOnReadOnlyItem,
                Assert.Throws <InvalidOperationException>(
                    () => source.AddMember(navigationProperty)).Message);

            Assert.Equal(0, source.Members.Count);

            source.AddNavigationProperty(navigationProperty);

            Assert.True(source.IsReadOnly);
            Assert.Equal(1, source.Members.Count);
            Assert.Same(navigationProperty, source.Members[0]);

            Assert.Equal(
                Resources.Strings.OperationOnReadOnlyItem,
                Assert.Throws <InvalidOperationException>(
                    () => source.AddMember(navigationProperty)).Message);
        }
        public void Can_get_association_ends_from_association_set()
        {
            var sourceEnd = new AssociationEndMember("S", new EntityType("E", "N", DataSpace.CSpace));
            var targetEnd = new AssociationEndMember("T", new EntityType("E", "N", DataSpace.CSpace));

            var associationType
                = new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace);

            associationType.AddKeyMember(targetEnd);
            associationType.AddKeyMember(sourceEnd);

            var associationSet = new AssociationSet("A", associationType);

            Assert.Null(associationSet.SourceEnd);
            Assert.Null(associationSet.TargetEnd);

            associationSet.AddAssociationSetEnd(new AssociationSetEnd(new EntitySet(), associationSet, sourceEnd));
            associationSet.AddAssociationSetEnd(new AssociationSetEnd(new EntitySet(), associationSet, targetEnd));

            Assert.Same(sourceEnd, associationSet.SourceEnd);
            Assert.Same(targetEnd, associationSet.TargetEnd);
        }
Esempio n. 47
0
        /// <summary>
        /// Creates a read-only AssociationType instance from the specified parameters.
        /// </summary>
        /// <param name="name">The name of the association type.</param>
        /// <param name="namespaceName">The namespace of the association type.</param>
        /// <param name="foreignKey">Flag that indicates a foreign key (FK) relationship.</param>
        /// <param name="dataSpace">The data space for the association type.</param>
        /// <param name="sourceEnd">The source association end member.</param>
        /// <param name="targetEnd">The target association end member.</param>
        /// <param name="constraint">A referential constraint.</param>
        /// <param name="metadataProperties">Metadata properties to be associated with the instance.</param>
        /// <returns>The newly created AssociationType instance.</returns>
        /// <exception cref="System.ArgumentException">The specified name is null or empty.</exception>
        /// <exception cref="System.ArgumentException">The specified namespace is null or empty.</exception>
        public static AssociationType Create(
            string name,
            string namespaceName,
            bool foreignKey,
            DataSpace dataSpace,
            AssociationEndMember sourceEnd,
            AssociationEndMember targetEnd,
            ReferentialConstraint constraint,
            IEnumerable <MetadataProperty> metadataProperties)
        {
            Check.NotEmpty(name, "name");
            Check.NotEmpty(namespaceName, "namespaceName");

            var instance = new AssociationType(name, namespaceName, foreignKey, dataSpace);

            if (sourceEnd != null)
            {
                instance.SourceEnd = sourceEnd;
            }

            if (targetEnd != null)
            {
                instance.TargetEnd = targetEnd;
            }

            if (constraint != null)
            {
                instance.AddReferentialConstraint(constraint);
            }

            if (metadataProperties != null)
            {
                instance.AddMetadataProperties(metadataProperties);
            }

            instance.SetReadOnly();

            return(instance);
        }
        internal AssociationType GetOSpaceAssociationType(
            AssociationType cSpaceAssociationType, Func <AssociationType> initializer)
        {
            Debug.Assert(cSpaceAssociationType.DataSpace == DataSpace.CSpace);

            var oSpaceAssociationTypes = GetOSpaceAssociationTypes();
            var index = cSpaceAssociationType.Index;

            Thread.MemoryBarrier();
            var oSpaceAssociationType = oSpaceAssociationTypes[index];

            if (oSpaceAssociationType == null)
            {
                oSpaceAssociationType = initializer();
                Debug.Assert(oSpaceAssociationType.DataSpace == DataSpace.OSpace);

                oSpaceAssociationType.Index   = index;
                oSpaceAssociationTypes[index] = oSpaceAssociationType;
                Thread.MemoryBarrier();
            }

            return(oSpaceAssociationType);
        }
Esempio n. 49
0
        public void Create_sets_properties_and_seals_the_instance()
        {
            var source     = new EntityType("Source", "Namespace", DataSpace.CSpace);
            var target     = new EntityType("Target", "Namespace", DataSpace.CSpace);
            var sourceEnd  = new AssociationEndMember("SourceEnd", source);
            var targetEnd  = new AssociationEndMember("TargetEnd", target);
            var constraint =
                new ReferentialConstraint(
                    sourceEnd,
                    targetEnd,
                    new[] { new EdmProperty("SourceProperty") },
                    new[] { new EdmProperty("TargetProperty") });
            var metadataProperty =
                new MetadataProperty(
                    "MetadataProperty",
                    TypeUsage.CreateDefaultTypeUsage(PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String)),
                    "value");
            var associationType =
                AssociationType.Create(
                    "AssociationType",
                    "Namespace",
                    true,
                    DataSpace.CSpace,
                    sourceEnd,
                    targetEnd,
                    constraint,
                    new[] { metadataProperty });

            Assert.Equal("Namespace.AssociationType", associationType.FullName);
            Assert.Equal(true, associationType.IsForeignKey);
            Assert.Equal(DataSpace.CSpace, associationType.DataSpace);
            Assert.Same(sourceEnd, associationType.SourceEnd);
            Assert.Same(targetEnd, associationType.TargetEnd);
            Assert.Same(constraint, associationType.Constraint);
            Assert.Same(metadataProperty, associationType.MetadataProperties.SingleOrDefault(p => p.Name == "MetadataProperty"));
            Assert.True(associationType.IsReadOnly);
        }
        internal AssociationSet FindCSpaceAssociationSet(AssociationType associationType, string endName, EntitySet endEntitySet)
        {
            DebugCheck.NotNull(associationType);
            DebugCheck.NotEmpty(endName);
            DebugCheck.NotNull(endEntitySet);
            Debug.Assert(associationType.DataSpace == DataSpace.CSpace);

            var array = GetCSpaceAssociationTypeToSetsMap();
            var index = associationType.Index;

            var objectAtIndex = array[index];

            if (objectAtIndex == null)
            {
                return(null);
            }

            var associationSet = objectAtIndex as AssociationSet;

            if (associationSet != null)
            {
                return(associationSet.AssociationSetEnds[endName].EntitySet == endEntitySet ? associationSet : null);
            }

            var items = (AssociationSet[])objectAtIndex;

            for (var i = 0; i < items.Length; i++)
            {
                associationSet = items[i];
                if (associationSet.AssociationSetEnds[endName].EntitySet == endEntitySet)
                {
                    return(associationSet);
                }
            }

            return(null);
        }
Esempio n. 51
0
        /// <summary>
        /// Creates a read-only AssociationSet instance from the specified parameters.
        /// </summary>
        /// <param name="name">The name of the association set.</param>
        /// <param name="type">The association type of the elements in the association set.</param>
        /// <param name="sourceSet">The entity set for the source association set end.</param>
        /// <param name="targetSet">The entity set for the target association set end.</param>
        /// <param name="metadataProperties">Metadata properties to be associated with the instance.</param>
        /// <returns>The newly created AssociationSet instance.</returns>
        /// <exception cref="System.ArgumentException">The specified name is null or empty.</exception>
        /// <exception cref="System.ArgumentNullException">The specified association type is null.</exception>
        /// <exception cref="System.ArgumentException">
        /// The entity type of one of the ends of the specified
        /// association type does not match the entity type of the corresponding entity set end.
        /// </exception>
        public static AssociationSet Create(
            string name,
            AssociationType type,
            EntitySet sourceSet,
            EntitySet targetSet,
            IEnumerable <MetadataProperty> metadataProperties)
        {
            Check.NotEmpty(name, "name");
            Check.NotNull(type, "type");

            if (!CheckEntitySetAgainstEndMember(sourceSet, type.SourceEnd) ||
                !CheckEntitySetAgainstEndMember(targetSet, type.TargetEnd))
            {
                throw new ArgumentException(Strings.AssociationSet_EndEntityTypeMismatch);
            }

            var instance = new AssociationSet(name, type);

            if (sourceSet != null)
            {
                instance.SourceSet = sourceSet;
            }

            if (targetSet != null)
            {
                instance.TargetSet = targetSet;
            }

            if (metadataProperties != null)
            {
                instance.AddMetadataProperties(metadataProperties.ToList());
            }

            instance.SetReadOnly();

            return(instance);
        }
Esempio n. 52
0
        public static void Create_sets_properties_and_seals_the_instance()
        {
            var typeUsage       = TypeUsage.CreateDefaultTypeUsage(PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String));
            var associationType = new AssociationType("AssociationType", "Namespace", true, DataSpace.CSpace);
            var source          = new EntityType("Source", "Namespace", DataSpace.CSpace);
            var target          = new EntityType("Target", "Namespace", DataSpace.CSpace);
            var sourceEnd       = new AssociationEndMember("SourceEnd", source);
            var targetEnd       = new AssociationEndMember("TargetEnd", target);

            var navigationProperty =
                NavigationProperty.Create(
                    "NavigationProperty",
                    typeUsage,
                    associationType,
                    sourceEnd,
                    targetEnd,
                    new[]
            {
                new MetadataProperty(
                    "TestProperty",
                    TypeUsage.CreateDefaultTypeUsage(PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String)),
                    "value"),
            });

            Assert.Equal("NavigationProperty", navigationProperty.Name);
            Assert.Same(typeUsage, navigationProperty.TypeUsage);
            Assert.Same(associationType, navigationProperty.RelationshipType);
            Assert.Same(sourceEnd, navigationProperty.FromEndMember);
            Assert.Same(targetEnd, navigationProperty.ToEndMember);
            Assert.True(navigationProperty.IsReadOnly);

            var metadataProperty = navigationProperty.MetadataProperties.SingleOrDefault(p => p.Name == "TestProperty");

            Assert.NotNull(metadataProperty);
            Assert.Equal("value", metadataProperty.Value);
        }
        public static void Create_sets_properties_and_seals_the_instance()
        {
            var typeUsage       = TypeUsage.CreateDefaultTypeUsage(PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String));
            var associationType = new AssociationType("AssociationType", "Namespace", true, DataSpace.CSpace);
            var source          = new EntityType("Source", "Namespace", DataSpace.CSpace);
            var target          = new EntityType("Target", "Namespace", DataSpace.CSpace);
            var sourceEnd       = new AssociationEndMember("SourceEnd", source);
            var targetEnd       = new AssociationEndMember("TargetEnd", target);

            var navigationProperty =
                NavigationProperty.Create(
                    "NavigationProperty",
                    typeUsage,
                    associationType,
                    sourceEnd,
                    targetEnd);

            Assert.Equal("NavigationProperty", navigationProperty.Name);
            Assert.Same(typeUsage, navigationProperty.TypeUsage);
            Assert.Same(associationType, navigationProperty.RelationshipType);
            Assert.Same(sourceEnd, navigationProperty.FromEndMember);
            Assert.Same(targetEnd, navigationProperty.ToEndMember);
            Assert.True(navigationProperty.IsReadOnly);
        }
Esempio n. 54
0
        public void Create_throws_argument_exception_when_called_with_invalid_arguments()
        {
            var source     = new EntityType("Source", "Namespace", DataSpace.CSpace);
            var target     = new EntityType("Target", "Namespace", DataSpace.CSpace);
            var sourceEnd  = new AssociationEndMember("SourceEnd", source);
            var targetEnd  = new AssociationEndMember("TargetEnd", target);
            var constraint =
                new ReferentialConstraint(
                    sourceEnd,
                    targetEnd,
                    new[] { new EdmProperty("SourceProperty") },
                    new[] { new EdmProperty("TargetProperty") });
            var metadataProperty =
                new MetadataProperty(
                    "MetadataProperty",
                    TypeUsage.CreateDefaultTypeUsage(PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String)),
                    "value");

            Assert.Throws <ArgumentException>(
                () => AssociationType.Create(
                    null,
                    "Namespace",
                    true,
                    DataSpace.CSpace,
                    sourceEnd,
                    targetEnd,
                    constraint,
                    new[] { metadataProperty }));

            Assert.Throws <ArgumentException>(
                () => AssociationType.Create(
                    String.Empty,
                    "Namespace",
                    true,
                    DataSpace.CSpace,
                    sourceEnd,
                    targetEnd,
                    constraint,
                    new[] { metadataProperty }));

            Assert.Throws <ArgumentException>(
                () => AssociationType.Create(
                    "AssociationType",
                    null,
                    true,
                    DataSpace.CSpace,
                    sourceEnd,
                    targetEnd,
                    constraint,
                    new[] { metadataProperty }));

            Assert.Throws <ArgumentException>(
                () => AssociationType.Create(
                    "AssociationType",
                    String.Empty,
                    true,
                    DataSpace.CSpace,
                    sourceEnd,
                    targetEnd,
                    constraint,
                    new[] { metadataProperty }));
        }
        public void Create_checks_each_EntitySet_parameter_against_corresponding_AssociationEndMember()
        {
            var source    = new EntityType("Source", "Namespace", DataSpace.CSpace);
            var target    = new EntityType("Target", "Namespace", DataSpace.CSpace);
            var other     = new EntityType("Other", "Namespace", DataSpace.CSpace);
            var sourceSet = new EntitySet("SourceSet", "Schema", "Table", "Query", source);
            var targetSet = new EntitySet("TargetSet", "Schema", "Table", "Query", target);
            var otherSet  = new EntitySet("OtherSet", "Schema", "Table", "Query", other);
            var sourceEnd = new AssociationEndMember("SourceEnd", source);
            var targetEnd = new AssociationEndMember("TargetEnd", target);

            var associationTypeWithNonNullEndMembers =
                AssociationType.Create(
                    "AssociationType",
                    "Namespace",
                    true,
                    DataSpace.CSpace,
                    sourceEnd,
                    targetEnd,
                    null,
                    null);

            var associationTypeWithNullEndMembers =
                AssociationType.Create(
                    "AssociationType",
                    "Namespace",
                    true,
                    DataSpace.CSpace,
                    null, // sourceEnd
                    null, // targetEnd
                    null,
                    null);

            Assert.NotNull(
                AssociationSet.Create(
                    "AssociationSet",
                    associationTypeWithNonNullEndMembers,
                    sourceSet,
                    targetSet,
                    null));

            Assert.NotNull(
                AssociationSet.Create(
                    "AssociationSet",
                    associationTypeWithNullEndMembers,
                    null, // sourceSet
                    null, // targetSet
                    null));

            Assert.Equal(
                Resources.Strings.AssociationSet_EndEntityTypeMismatch,
                Assert.Throws <ArgumentException>(
                    () => AssociationSet.Create(
                        "AssociationSet",
                        associationTypeWithNonNullEndMembers,
                        otherSet,
                        targetSet,
                        null)).Message);

            Assert.Equal(
                Resources.Strings.AssociationSet_EndEntityTypeMismatch,
                Assert.Throws <ArgumentException>(
                    () => AssociationSet.Create(
                        "AssociationSet",
                        associationTypeWithNonNullEndMembers,
                        sourceSet,
                        otherSet,
                        null)).Message);

            Assert.Equal(
                Resources.Strings.AssociationSet_EndEntityTypeMismatch,
                Assert.Throws <ArgumentException>(
                    () => AssociationSet.Create(
                        "AssociationSet",
                        associationTypeWithNonNullEndMembers,
                        null, // sourceSet
                        targetSet,
                        null)).Message);

            Assert.Equal(
                Resources.Strings.AssociationSet_EndEntityTypeMismatch,
                Assert.Throws <ArgumentException>(
                    () => AssociationSet.Create(
                        "AssociationSet",
                        associationTypeWithNonNullEndMembers,
                        sourceSet,
                        null, // targetSet
                        null)).Message);

            Assert.Equal(
                Resources.Strings.AssociationSet_EndEntityTypeMismatch,
                Assert.Throws <ArgumentException>(
                    () => AssociationSet.Create(
                        "AssociationSet",
                        associationTypeWithNullEndMembers,
                        null, // sourceSet
                        targetSet,
                        null)).Message);

            Assert.Equal(
                Resources.Strings.AssociationSet_EndEntityTypeMismatch,
                Assert.Throws <ArgumentException>(
                    () => AssociationSet.Create(
                        "AssociationSet",
                        associationTypeWithNullEndMembers,
                        sourceSet,
                        null, // targetSet
                        null)).Message);
        }
        internal AssociationType GetCSpaceAssociationType(AssociationType osAssociationType)
        {
            Debug.Assert(osAssociationType.Index >= 0);

            return(_csAssociationTypes[osAssociationType.Index]);
        }
Esempio n. 57
0
        /// <summary>
        /// Removes an association type from the model.
        /// </summary>
        /// <param name="item">The AssociationType instance to be removed.</param>
        public void RemoveItem(AssociationType item)
        {
            Check.NotNull(item, "item");

            _associationTypes.Remove(item);
        }
Esempio n. 58
0
 // <summary>
 // Initializes a new instance of AssocationSet with the given name and the association type
 // </summary>
 // <param name="name"> The name of the Assocation set </param>
 // <param name="associationType"> The association type of the entities that this associationship set type contains </param>
 internal AssociationSet(string name, AssociationType associationType)
     : base(name, null, null, null, associationType)
 {
 }
Esempio n. 59
0
 private void InternalVisitEdmAssociationType(AssociationType item)
 {
     this._schemaWriter.WriteAssociationTypeElementHeader(item);
     base.VisitEdmAssociationType(item);
     this._schemaWriter.WriteEndElement();
 }
 internal void WriteAssociationTypeElementHeader(AssociationType associationType)
 {
     this._xmlWriter.WriteStartElement("Association");
     this._xmlWriter.WriteAttributeString("Name", associationType.Name);
 }