Exemple #1
0
        /// <summary>
        /// Configures the referential constraint with the dependent and principal property pair.
        /// </summary>
        /// <param name="constraint">The dependent and principal property pair.</param>
        public NavigationPropertyConfiguration HasConstraint(KeyValuePair <PropertyInfo, PropertyInfo> constraint)
        {
            if (constraint.Key == null)
            {
                throw Error.ArgumentNull("dependentPropertyInfo");
            }

            if (constraint.Value == null)
            {
                throw Error.ArgumentNull("principalPropertyInfo");
            }

            if (Multiplicity == EdmMultiplicity.Many)
            {
                throw Error.NotSupported(SRResources.ReferentialConstraintOnManyNavigationPropertyNotSupported,
                                         Name, DeclaringEntityType.ClrType.FullName);
            }

            if (ValidateConstraint(constraint))
            {
                return(this);
            }

            EntityTypeConfiguration principalEntity = DeclaringEntityType.ModelBuilder.StructuralTypes
                                                      .OfType <EntityTypeConfiguration>().FirstOrDefault(e => e.ClrType == RelatedClrType);

            Contract.Assert(principalEntity != null);

            PrimitivePropertyConfiguration principal = principalEntity.AddPrimitiveProperty(constraint.Value);
            PrimitivePropertyConfiguration dependent = DeclaringEntityType.AddPrimitiveProperty(constraint.Key);

            // If the navigation property on which the referential constraint is defined or the principal property
            // is nullable, then the dependent property MUST be nullable.
            if (Multiplicity == EdmMultiplicity.ZeroOrOne || principal.OptionalProperty)
            {
                dependent.OptionalProperty = true;
            }

            // If both the navigation property and the principal property are not nullable,
            // then the dependent property MUST be marked with the Nullable="false" attribute value.
            if (Multiplicity == EdmMultiplicity.One && !principal.OptionalProperty)
            {
                dependent.OptionalProperty = false;
            }

            _referentialConstraint.Add(constraint);
            return(this);
        }