/// <summary>
        /// Returns the association information for the specified navigation property.
        /// </summary>
        /// <param name="navigationProperty">The navigation property to return association information for</param>
        /// <returns>The association info</returns>
        internal AssociationInfo GetAssociationInfo(NavigationProperty navigationProperty)
        {
            lock (this._associationMap)
            {
                string associationName = navigationProperty.RelationshipType.FullName;
                AssociationInfo associationInfo = null;
                if (!this._associationMap.TryGetValue(associationName, out associationInfo))
                {
                    AssociationType associationType = (AssociationType)navigationProperty.RelationshipType;

                    if (!associationType.ReferentialConstraints.Any())
                    {
                        // We only support EF models where FK info is part of the model.
                        throw new NotSupportedException(
                            string.Format(CultureInfo.CurrentCulture,
                            Resource.LinqToEntitiesProvider_UnableToRetrieveAssociationInfo, associationName));
                    }

                    associationInfo = new AssociationInfo();
                    associationInfo.FKRole = associationType.ReferentialConstraints[0].ToRole.Name;
                    associationInfo.Name = this.GetAssociationName(navigationProperty, associationInfo.FKRole);
                    associationInfo.ThisKey = associationType.ReferentialConstraints[0].ToProperties.Select(p => p.Name).ToArray();
                    associationInfo.OtherKey = associationType.ReferentialConstraints[0].FromProperties.Select(p => p.Name).ToArray();
                    associationInfo.IsRequired = associationType.RelationshipEndMembers[0].RelationshipMultiplicity == RelationshipMultiplicity.One;

                    this._associationMap[associationName] = associationInfo;
                }

                return associationInfo;
            }
        }
        public static AssociationEndMember GetFromEnd(this NavigationProperty navProp)
        {
            DebugCheck.NotNull(navProp.Association);

            return(navProp.Association.SourceEnd == navProp.ResultEnd
                       ? navProp.Association.TargetEnd
                       : navProp.Association.SourceEnd);
        }
Ejemplo n.º 3
0
 public static EntityType TargetEntity(NavigationProperty property)
 {
     if (property == null)
     {
         return(null);
     }
     return(property.ToEndMember.GetEntityType());
 }
Ejemplo n.º 4
0
 public IEnumerable <IFilterAttribute> AttributesFor(NavigationProperty property)
 {
     return(withCache(new Signature(property), () =>
     {
         var info = mapper.Map(property);
         return info.GetAttributes <IFilterAttribute>();
     }));
 }
Ejemplo n.º 5
0
        private static void SetEndNavigationProperty(NavigationProperty navProp, string value)
        {
            var     cpc = PropertyWindowViewModelHelper.GetCommandProcessorContext();
            Command c   = new EntityDesignRenameCommand(navProp, value, true);
            var     cp  = new CommandProcessor(cpc, c);

            cp.Invoke();
        }
Ejemplo n.º 6
0
 private static string GetEndNavigationProperty(NavigationProperty navProp)
 {
     if (navProp == null)
     {
         return(String.Empty);
     }
     return(navProp.LocalName.Value);
 }
Ejemplo n.º 7
0
 private void RemoveNotNullCondition(NavigationProperty navigationProperty)
 {
     foreach (var column in navigationProperty.Mapping.Select(pm => pm.Column))
     {
         RemoveNotNullCondition(column);
     }
     RemoveNavigationPropertyMappingListeners(navigationProperty);
 }
Ejemplo n.º 8
0
        public static bool IsSymetric(NavigationProperty property)
        {
            AssociationTypes associationType = GetAssociationType(property);

            return
                (associationType == AssociationTypes.ZeroOrOneToZeroOrOne ||
                 associationType == AssociationTypes.OneToOne);
        }
Ejemplo n.º 9
0
        /// <inheritdoc/>
        protected override void SetOperations(OpenApiPathItem item)
        {
            IEdmEntitySet             entitySet = NavigationSource as IEdmEntitySet;
            IEdmVocabularyAnnotatable target    = entitySet;

            if (target == null)
            {
                target = NavigationSource as IEdmSingleton;
            }

            string navigationPropertyPath = String.Join("/",
                                                        Path.Segments.Where(s => !(s is ODataKeySegment || s is ODataNavigationSourceSegment)).Select(e => e.Identifier));

            NavigationRestrictionsType    navigation  = Context.Model.GetRecord <NavigationRestrictionsType>(target, CapabilitiesConstants.NavigationRestrictions);
            NavigationPropertyRestriction restriction = navigation?.RestrictedProperties?.FirstOrDefault(r => r.NavigationProperty == navigationPropertyPath);

            // verify using individual first
            if (restriction != null && restriction.Navigability != null && restriction.Navigability.Value == NavigationType.None)
            {
                return;
            }

            if (restriction == null || restriction.Navigability == null)
            {
                // if the individual has not navigability setting, use the global navigability setting
                if (navigation != null && navigation.Navigability != null && navigation.Navigability.Value == NavigationType.None)
                {
                    // Default navigability for all navigation properties of the annotation target.
                    // Individual navigation properties can override this value via `RestrictedProperties/Navigability`.
                    return;
                }
            }

            // So far, we only consider the non-containment
            Debug.Assert(!NavigationProperty.ContainsTarget);

            // Create the ref
            if (NavigationProperty.TargetMultiplicity() == EdmMultiplicity.Many)
            {
                ODataSegment penultimateSegment = Path.Segments.Reverse().Skip(1).First();
                if (penultimateSegment is ODataKeySegment)
                {
                    // Collection-valued: DELETE ~/entityset/{key}/collection-valued-Nav/{key}/$ref
                    AddDeleteOperation(item, restriction);
                }
                else
                {
                    AddReadOperation(item, restriction);
                    AddInsertOperation(item, restriction);
                }
            }
            else
            {
                AddReadOperation(item, restriction);
                AddUpdateOperation(item, restriction);
                AddDeleteOperation(item, restriction);
            }
        }
Ejemplo n.º 10
0
 /// <summary>
 /// Adds initialization for a property if any is needed
 /// </summary>
 /// <param name="navigationProperty">The property to initialize</param>
 /// <param name="parentClassConstructor">The constructor to add to</param>
 protected virtual void DeclareOptionalPropertyInitializer(NavigationProperty navigationProperty, CodeConstructor parentClassConstructor)
 {
     // right now, we only need to initialize collection navigations
     if (navigationProperty.ToAssociationEnd.Multiplicity == EndMultiplicity.Many)
     {
         var type = this.GetPropertyType(navigationProperty, CodeGenerationTypeUsage.Instantiation);
         parentClassConstructor.Statements.Add(Code.This().Property(navigationProperty.Name).Assign(Code.New(type)));
     }
 }
Ejemplo n.º 11
0
        private IEnumerable <string> GetForeignKeys(NavigationProperty navigationProperty)
        {
            var associations = (AssociationType)navigationProperty.RelationshipType;

            return(associations.ReferentialConstraints
                   .Single()
                   .ToProperties
                   .Select(x => x.Name));
        }
        public static AssociationType ForeignKeyFor(this DbContext context, Type source, Type target)
        {
            MetadataWorkspace  metadata             = ((IObjectContextAdapter)context).ObjectContext.MetadataWorkspace;
            ItemCollection     objectItemCollection = ((ObjectItemCollection)metadata.GetItemCollection(DataSpace.OSpace));
            EntityType         sourceItem           = objectItemCollection.Where(o => o is EntityType && ((EntityType)o).GetReferenceType().ElementType.FullName == GetBaseTypeFor(source).FullName).FirstOrDefault() as EntityType;
            NavigationProperty property             = (sourceItem as EntityType).NavigationProperties.Where(p => ((p.ToEndMember.MetadataProperties["TypeUsage"].Value as TypeUsage).EdmType.MetadataProperties["ElementType"].Value as EntityType).FullName == GetBaseTypeFor(target).FullName).FirstOrDefault();

            return(metadata.GetItems <AssociationType>(DataSpace.CSpace).FirstOrDefault(a => a.IsForeignKey && a.ReferentialConstraints[0].ToRole.Name.Equals(property.FromEndMember.Name) && a.ReferentialConstraints[0].FromRole.Name.Equals(property.ToEndMember.Name)));
        }
        /// <inheritdoc/>
        protected override void SetOperations(OpenApiPathItem item)
        {
            IEdmEntitySet             entitySet = NavigationSource as IEdmEntitySet;
            IEdmVocabularyAnnotatable target    = entitySet;

            if (target == null)
            {
                target = NavigationSource as IEdmSingleton;
            }

            NavigationRestrictionsType navSourceRestrictionType = Context.Model.GetRecord <NavigationRestrictionsType>(target, CapabilitiesConstants.NavigationRestrictions);
            NavigationRestrictionsType navPropRestrictionType   = Context.Model.GetRecord <NavigationRestrictionsType>(NavigationProperty, CapabilitiesConstants.NavigationRestrictions);

            NavigationPropertyRestriction restriction = navSourceRestrictionType?.RestrictedProperties?
                                                        .FirstOrDefault(r => r.NavigationProperty == Path.NavigationPropertyPath())
                                                        ?? navPropRestrictionType?.RestrictedProperties?.FirstOrDefault();

            // Check whether the navigation property should be part of the path
            if (EdmModelHelper.NavigationRestrictionsAllowsNavigability(navSourceRestrictionType, restriction) == false ||
                EdmModelHelper.NavigationRestrictionsAllowsNavigability(navPropRestrictionType, restriction) == false)
            {
                return;
            }

            // containment: Get / (Post - Collection | Patch - Single)
            // non-containment: Get
            AddGetOperation(item, restriction);

            if (NavigationProperty.ContainsTarget)
            {
                if (NavigationProperty.TargetMultiplicity() == EdmMultiplicity.Many)
                {
                    if (LastSegmentIsKeySegment)
                    {
                        UpdateRestrictionsType updateEntity = Context.Model.GetRecord <UpdateRestrictionsType>(_entityType);
                        if (updateEntity?.IsUpdatable ?? true)
                        {
                            AddUpdateOperation(item, restriction);
                        }
                    }
                    else
                    {
                        InsertRestrictionsType insert = restriction?.InsertRestrictions;
                        if (insert?.IsInsertable ?? true)
                        {
                            AddOperation(item, OperationType.Post);
                        }
                    }
                }
                else
                {
                    AddUpdateOperation(item, restriction);
                }
            }

            AddDeleteOperation(item, restriction);
        }
        /// <summary>
        /// True if the source end of the specified navigation property is the principal in an identifying relationship.
        /// or if the source end has cascade delete defined.
        /// </summary>
        public bool IsCascadeDeletePrincipal(NavigationProperty navProperty)
        {
            if (navProperty == null)
            {
                throw new ArgumentNullException("navProperty");
            }

            return(IsCascadeDeletePrincipal((AssociationEndMember)navProperty.FromEndMember));
        }
        /// <summary>
        /// Gets the collection of properties that are on the dependent end of a referential constraint for the specified navigation property.
        /// Requires: The association has a referential constraint.
        /// </summary>
        public ReadOnlyMetadataCollection <EdmProperty> GetDependentProperties(NavigationProperty navProperty)
        {
            if (navProperty == null)
            {
                throw new ArgumentNullException("navProperty");
            }

            return(((AssociationType)navProperty.RelationshipType).ReferentialConstraints[0].ToProperties);
        }
Ejemplo n.º 16
0
 internal void Dump(NavigationProperty navProp, string name)
 {
     this.Begin(name);
     this.Begin("NavigationProperty", "Name", (object)navProp.Name, "RelationshipTypeName", (object)navProp.RelationshipType.FullName, "ToEndMemberName", (object)navProp.ToEndMember.Name);
     this.Dump((EdmType)navProp.DeclaringType, "DeclaringType");
     this.Dump(navProp.TypeUsage, "PropertyType");
     this.End("NavigationProperty");
     this.End(name);
 }
        private NavigationProperty GetOtherNavigationProperty(NavigationProperty navigationProperty)
        {
            var other = navigationProperty
                        .ToEndMember
                        .GetEntityType()
                        .NavigationProperties.Single(n => n.RelationshipType == navigationProperty.RelationshipType && n != navigationProperty);

            return(other);
        }
Ejemplo n.º 18
0
        /// <summary>
        ///     Utility method to retrieve the 'To' AssociationEndMember of a NavigationProperty
        /// </summary>
        /// <param name="property"> The navigation property </param>
        /// <returns> The AssociationEndMember that is the target of the navigation operation represented by the NavigationProperty </returns>
        private AssociationEndMember GetNavigationPropertyTargetEnd(NavigationProperty property)
        {
            var relationship = Metadata.GetItem <AssociationType>(property.RelationshipType.FullName, DataSpace.CSpace);

            Debug.Assert(
                relationship.AssociationEndMembers.Contains(property.ToEndMember.Name),
                "Association does not declare member referenced by Navigation property?");
            return(relationship.AssociationEndMembers[property.ToEndMember.Name]);
        }
Ejemplo n.º 19
0
        /// <summary>
        ///     Retrieves the Entity (result or element) type produced by a Navigation Property.
        /// </summary>
        /// <param name="navProp"> The navigation property </param>
        /// <returns> The Entity type produced by the navigation property. This may be the immediate result type (if the result is at most one) or the element type of the result type, otherwise. </returns>
        private static EntityType EntityTypeFromResultType(NavigationProperty navProp)
        {
            EntityType retType = null;

            TryGetEntityType(navProp.TypeUsage, out retType);
            // Currently, navigation properties may only return an Entity or Collection<Entity> result
            Debug.Assert(retType != null, "Navigation property has non-Entity and non-Entity collection result type?");
            return(retType);
        }
Ejemplo n.º 20
0
        public virtual IRelatedEnd GetRelatedEnd(string navigationProperty)
        {
            EdmMember edmMember;

            this.EdmEntityType.Members.TryGetValue(navigationProperty, false, out edmMember);
            NavigationProperty navigationProperty1 = (NavigationProperty)edmMember;

            return(this._internalContext.ObjectContext.ObjectStateManager.GetRelationshipManager(this.Entity).GetRelatedEnd(navigationProperty1.RelationshipType.FullName, navigationProperty1.ToEndMember.Name));
        }
Ejemplo n.º 21
0
        private Type GetNavigationTargetType(NavigationProperty navigationProperty)
        {
            MetadataWorkspace metadataWorkspace = this._internalContext.ObjectContext.MetadataWorkspace;

            System.Data.Entity.Core.Metadata.Edm.EntityType entityType = navigationProperty.RelationshipType.RelationshipEndMembers.Single <RelationshipEndMember>((Func <RelationshipEndMember, bool>)(e => navigationProperty.ToEndMember.Name == e.Name)).GetEntityType();
            StructuralType objectSpaceType = metadataWorkspace.GetObjectSpaceType((StructuralType)entityType);

            return(((ObjectItemCollection)metadataWorkspace.GetItemCollection(DataSpace.OSpace)).GetClrType(objectSpaceType));
        }
Ejemplo n.º 22
0
 public static AssociationEndMember GetFromEnd(
     this NavigationProperty navProp)
 {
     if (navProp.Association.SourceEnd != navProp.ResultEnd)
     {
         return(navProp.Association.SourceEnd);
     }
     return(navProp.Association.TargetEnd);
 }
Ejemplo n.º 23
0
 public static PropertyInfo GetProperty(this NavigationProperty navProp, Assembly contextAssembly)
 {
     return(navProp
            .FromEndMember
            .GetEntityType()
            .GetClrType(contextAssembly)
            .GetProperty(navProp.Name,
                         BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.SetProperty));
 }
Ejemplo n.º 24
0
 private void WriteNavigationPropertyElement(NavigationProperty member)
 {
     _writer.WriteStartElement(XmlConstants.NavigationProperty);
     _writer.WriteAttributeString(XmlConstants.Name, member.Name);
     _writer.WriteAttributeString(XmlConstants.Relationship, member.RelationshipType.FullName);
     _writer.WriteAttributeString(XmlConstants.FromRole, member.FromEndMember.Name);
     _writer.WriteAttributeString(XmlConstants.ToRole, member.ToEndMember.Name);
     _writer.WriteEndElement();
 }
Ejemplo n.º 25
0
        public static AssociationTypes GetAssociationType(NavigationProperty property)
        {
            switch (property.FromEndMember.RelationshipMultiplicity)
            {
            case RelationshipMultiplicity.Many:
                switch (property.ToEndMember.RelationshipMultiplicity)
                {
                case RelationshipMultiplicity.Many:
                    return(AssociationTypes.ManyToMany);

                case RelationshipMultiplicity.ZeroOrOne:
                    return(AssociationTypes.ManyToZeroOrOne);

                case RelationshipMultiplicity.One:
                    return(AssociationTypes.ManyToOne);

                default:
                    throw new ApplicationException("Impossible case");
                }

            case RelationshipMultiplicity.ZeroOrOne:
                switch (property.ToEndMember.RelationshipMultiplicity)
                {
                case RelationshipMultiplicity.Many:
                    return(AssociationTypes.ZeroOrOneToMany);

                case RelationshipMultiplicity.ZeroOrOne:
                    return(AssociationTypes.ZeroOrOneToZeroOrOne);

                case RelationshipMultiplicity.One:
                    return(AssociationTypes.ZeroOrOneToOne);

                default:
                    throw new ApplicationException("Impossible case");
                }

            case RelationshipMultiplicity.One:
                switch (property.ToEndMember.RelationshipMultiplicity)
                {
                case RelationshipMultiplicity.Many:
                    return(AssociationTypes.OneToMany);

                case RelationshipMultiplicity.ZeroOrOne:
                    return(AssociationTypes.OneToZeroOrOne);

                case RelationshipMultiplicity.One:
                    return(AssociationTypes.OneToOne);

                default:
                    throw new ApplicationException("Impossible case");
                }

            default:
                throw new ApplicationException("Impossible case");
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        ///     Creates a command of that can change a Navigation Property
        /// </summary>
        /// <param name="association">The association to use.</param>
        /// <param name="property">The navigation property to change</param>
        internal ChangeNavigationPropertyCommand(NavigationProperty property, Association association)
        {
            if (property == null)
            {
                throw new ArgumentNullException("property");
            }

            _property    = property;
            _association = association;
        }
Ejemplo n.º 27
0
 internal void WriteNavigationPropertyElementHeader(NavigationProperty member)
 {
     _xmlWriter.WriteStartElement(XmlConstants.NavigationProperty);
     _xmlWriter.WriteAttributeString(XmlConstants.Name, member.Name);
     _xmlWriter.WriteAttributeString(
         XmlConstants.Relationship,
         GetQualifiedTypeName(XmlConstants.Self, member.Association.Name));
     _xmlWriter.WriteAttributeString(XmlConstants.FromRole, member.GetFromEnd().Name);
     _xmlWriter.WriteAttributeString(XmlConstants.ToRole, member.ResultEnd.Name);
 }
        private ForeignKeyRelationship CreateForeignKeyRelationship(NavigationProperty navigationProperty)
        {
            var relationship = new ForeignKeyRelationship()
            {
                Source = navigationProperty,
                Target = this.GetOtherNavigationProperty(navigationProperty),
            };

            return(relationship);
        }
Ejemplo n.º 29
0
        private EntityConstructorView Create(NavigationProperty property)
        {
            var view = new EntityConstructorView()
            {
                Name     = this.codeGenEscaper.Escape(property.Name),
                TypeName = this.GetTypeName(property.ToEndMember)
            };

            return(view);
        }
 public void RemoveChildren(EntityKey parentEntityKey, NavigationProperty navProp) {
   var navChildrenList = GetNavChildrenList(parentEntityKey, false);
   if (navChildrenList == null) return;
   var ix = navChildrenList.IndexOf(nc => nc.NavigationProperty == navProp);
   if (ix != -1) return;
   navChildrenList.RemoveAt(ix);
   if (navChildrenList.Count == 0) {
     _map.Remove(parentEntityKey);
   }
 }
Ejemplo n.º 31
0
 /// <summary>
 /// Gets the EDM type for this segment.
 /// </summary>
 /// <param name="previousEdmType">The EDM type of the previous path segment.</param>
 /// <returns>
 /// The EDM type for this segment.
 /// </returns>
 public override IEdmType GetEdmType(IEdmType previousEdmType)
 {
     if (NavigationProperty != null)
     {
         return(NavigationProperty.Partner.Multiplicity() == EdmMultiplicity.Many ?
                (IEdmType)NavigationProperty.ToEntityType().GetCollection() :
                (IEdmType)NavigationProperty.ToEntityType());
     }
     return(null);
 }
Ejemplo n.º 32
0
        public ManyToManyNavigation(NavigationProperty hasManyNavigationProperty)
        {
            this.HasMany = hasManyNavigationProperty;

            this.WithMany = this.HasMany
                            .ToEndMember
                            .GetEntityType()
                            .NavigationProperties
                            .Single(x => x.RelationshipType == hasManyNavigationProperty.RelationshipType && x != hasManyNavigationProperty);
        }
    public HashSet<IEntity> GetNavChildren(EntityKey entityKey, NavigationProperty navProp, bool createIfNotFound) {
      List<NavChildren> navChildrenList = GetNavChildrenList(entityKey, createIfNotFound);
      if (navChildrenList == null) return null;
      
      var navChildren = navChildrenList.FirstOrDefault(uc => uc.NavigationProperty == navProp);
      if (navChildren == null && createIfNotFound) {
        navChildren = new NavChildren() {NavigationProperty = navProp, Children = new HashSet<IEntity>() };
        navChildrenList.Add(navChildren);
      }

      var children = navChildren.Children;
      children.RemoveWhere( entity => entity.EntityAspect.EntityState.IsDetached());

      return children;
    }
Ejemplo n.º 34
0
    //public static EntityQuery BuildQuery(IEntity entity, NavigationProperty np) {
    //  var ekQuery = BuildQuery(entity.EntityAspect.EntityKey);
    //  var q = ekQuery.ExpandNonGeneric(np.Name);
    //  return q;
    //}

    /// <summary>
    /// Builds an <see cref="EntityQuery"/> to load the entities for the navigation property of the entity.
    /// </summary>
    public static EntityQuery BuildQuery(IEntity entity, NavigationProperty np)
    {
      if (np.IsScalar) {
        if (np.ForeignKeyNames.Count == 0) return null;
        var relatedKeyValues = np.ForeignKeyNames.Select(fk => entity.EntityAspect.GetValue(fk)).ToArray();
        var entityKey = new EntityKey(np.EntityType, relatedKeyValues);
        return BuildQuery(entityKey);
      }
      else {
        var inverseNp = np.Inverse;
        var fkNames = inverseNp != null ? inverseNp.ForeignKeyNames : np.InvForeignKeyNames;
        if (fkNames.Count == 0) return null;
        var keyValues = entity.EntityAspect.EntityKey.Values;

        var parameterExpr = Expression.Parameter(np.EntityType.ClrType, "t");
        var propExpressions = fkNames.Select(name => Expression.Property(parameterExpr, name));
        var fkExpression = BuildMultiEqualExpr(propExpressions, keyValues);

        var entityQuery = EntityQuery.Create(np.EntityType.ClrType);
        var queryLambda = Expression.Lambda(fkExpression, parameterExpr);
        return AddWhereClause(entityQuery, queryLambda);
      }
    }
        /// <summary>
        /// Returns a unique association name for the specified navigation property.
        /// </summary>
        /// <param name="navigationProperty">The navigation property</param>
        /// <param name="foreignKeyRoleName">The foreign key role name for the property's association</param>
        /// <returns>A unique association name for the specified navigation property.</returns>
        private string GetAssociationName(NavigationProperty navigationProperty, string foreignKeyRoleName)
        {
            RelationshipEndMember fromMember = navigationProperty.FromEndMember;
            RelationshipEndMember toMember = navigationProperty.ToEndMember;

            RefType toRefType = toMember.TypeUsage.EdmType as RefType;
            EntityType toEntityType = toRefType.ElementType as EntityType;

            RefType fromRefType = fromMember.TypeUsage.EdmType as RefType;
            EntityType fromEntityType = fromRefType.ElementType as EntityType;

            bool isForeignKey = navigationProperty.FromEndMember.Name == foreignKeyRoleName;
            string fromTypeName = isForeignKey ? fromEntityType.Name : toEntityType.Name;
            string toTypeName = isForeignKey ? toEntityType.Name : fromEntityType.Name;

            // names are always formatted non-FK side type name followed by FK side type name
            string associationName = string.Format(CultureInfo.InvariantCulture, "{0}_{1}", toTypeName, fromTypeName);
            associationName = MakeUniqueName(associationName, this._associationMap.Values.Select(p => p.Name));

            return associationName;
        }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="generator"></param>
 /// <param name="navigationProperty"></param>
 public NavigationPropertyEmitter(ClientApiGenerator generator, NavigationProperty navigationProperty, bool declaringTypeUsesStandardBaseType)
     : base(generator, navigationProperty, declaringTypeUsesStandardBaseType)
 {
 }
 internal NavigationPropertyDelete(NavigationProperty property)
 {
     _property = property;
 }
Ejemplo n.º 38
0
 public static EntityQuery BuildQuery(IEntity entity, NavigationProperty np) {
   var ekQuery = BuildQuery(entity.EntityAspect.EntityKey);
   var q = ekQuery.ExpandNonGeneric(np.Name);
   return q;
 }
 internal NavigationPropertyChange(NavigationProperty property)
 {
     _property = property;
 }
Ejemplo n.º 40
0
        /// <summary>
        /// Converts a navigation property from SOM to metadata
        /// </summary>
        /// <param name="declaringEntityType">entity type on which this navigation property was declared</param>
        /// <param name="somNavigationProperty">The SOM element to process</param>
        /// <param name="providerManifest">The provider manifest to be used for conversion</param>
        /// <param name="convertedItemCache">The item collection for currently existing metadata objects</param>
        /// <param name="newGlobalItems">The new GlobalItem objects that are created as a result of this conversion</param>
        /// <returns>The property object resulting from the convert</returns>
        private static NavigationProperty ConvertToNavigationProperty(
            EntityType declaringEntityType,
            Som.NavigationProperty somNavigationProperty,
            DbProviderManifest providerManifest,
            ConversionCache convertedItemCache,
            Dictionary<Som.SchemaElement, GlobalItem> newGlobalItems)
        {
            // Navigation properties cannot be primitive types, so we can ignore the possibility of having primitive type
            // facets
            var toEndEntityType = (EntityType)LoadSchemaElement(
                somNavigationProperty.Type,
                providerManifest,
                convertedItemCache,
                newGlobalItems);

            EdmType edmType = toEndEntityType;

            // Also load the relationship Type that this navigation property represents
            var relationshipType = (AssociationType)LoadSchemaElement(
                (Som.Relationship)somNavigationProperty.Relationship,
                providerManifest, convertedItemCache, newGlobalItems);

            Som.IRelationshipEnd somRelationshipEnd = null;
            somNavigationProperty.Relationship.TryGetEnd(somNavigationProperty.ToEnd.Name, out somRelationshipEnd);
            if (somRelationshipEnd.Multiplicity
                == RelationshipMultiplicity.Many)
            {
                edmType = toEndEntityType.GetCollectionType();
            }
            else
            {
                Debug.Assert(somRelationshipEnd.Multiplicity != RelationshipMultiplicity.Many);
                edmType = toEndEntityType;
            }

            TypeUsage typeUsage;
            if (somRelationshipEnd.Multiplicity
                == RelationshipMultiplicity.One)
            {
                typeUsage = TypeUsage.Create(
                    edmType,
                    new FacetValues
                        {
                            Nullable = false
                        });
            }
            else
            {
                typeUsage = TypeUsage.Create(edmType);
            }

            // We need to make sure that both the ends of the relationtype are initialized. If there are not, then we should
            // initialize them here
            InitializeAssociationEndMember(relationshipType, somNavigationProperty.ToEnd, toEndEntityType);
            InitializeAssociationEndMember(relationshipType, somNavigationProperty.FromEnd, declaringEntityType);

            // The type of the navigation property must be a ref or collection depending on which end they belong to
            var navigationProperty = new NavigationProperty(somNavigationProperty.Name, typeUsage);
            navigationProperty.RelationshipType = relationshipType;
            navigationProperty.ToEndMember = (RelationshipEndMember)relationshipType.Members[somNavigationProperty.ToEnd.Name];
            navigationProperty.FromEndMember = (RelationshipEndMember)relationshipType.Members[somNavigationProperty.FromEnd.Name];

            // Extract the optional Documentation
            if (somNavigationProperty.Documentation != null)
            {
                navigationProperty.Documentation = ConvertToDocumentation(somNavigationProperty.Documentation);
            }
            AddOtherContent(somNavigationProperty, navigationProperty);

            return navigationProperty;
        }
Ejemplo n.º 41
0
 public static NavigationProperty GetOtherEnd(NavigationProperty navProp)
 {
     var assoc = navProp.Store.ElementDirectory.FindElements<Association>().First(a => a.Name == navProp.Association);
     var relatedEntity = (assoc.End1RoleName == navProp.ModelClass.Name && assoc.End1NavigationProperty == navProp.Name) ? assoc.End2RoleName : assoc.End1RoleName;
     return navProp.Store.ElementDirectory.FindElements<ModelClass>().First(c => c.Name == relatedEntity).NavigationProperties.Find(np => np.Association == navProp.Association);
 }
Ejemplo n.º 42
0
 bool ValidateForeignkeyChange(bool newValue, NavigationProperty navProp, NavigationProperty otherEnd)
 {
     if (newValue)
         return (navProp.Multiplicity == Multiplicity.One || (navProp.Multiplicity == Multiplicity.ZeroOne && otherEnd.Multiplicity != Multiplicity.One));
     else
         return (otherEnd.Multiplicity == Multiplicity.One || (otherEnd.Multiplicity == Multiplicity.ZeroOne && navProp.Multiplicity != Multiplicity.One));
 }
Ejemplo n.º 43
0
        void SetForeignkey(NavigationProperty foreignkeyProp, NavigationProperty otherEnd)
        {
            otherEnd.IsForeignkey = false;
            var otherEndForeignkeyColumn = otherEnd.ModelClass.Fields.Find(f => f.Name == otherEnd.ForeignkeyColumn);
            if (otherEndForeignkeyColumn != null) otherEndForeignkeyColumn.Delete();
            otherEnd.ForeignkeyColumn = null;

            foreignkeyProp.IsForeignkey = true;
            foreignkeyProp.ForeignkeyColumn = ModelUtil.GetMemberName(otherEnd.ModelClass.Name + "Id", foreignkeyProp.ModelClass, false);
            var otherEndPrimaryKeyField = otherEnd.ModelClass.Fields.Find(f => f.IsPrimaryKey);
            var newForeignkeyField = new ModelField(foreignkeyProp.Store) { Name = foreignkeyProp.ForeignkeyColumn };
            CopyAttributesFrom(otherEndPrimaryKeyField, newForeignkeyField);
            foreignkeyProp.ModelClass.Fields.Add(newForeignkeyField);
        }
 public void AddChild(EntityKey parentEntityKey, NavigationProperty navProp, IEntity child) {
   var navChildren = GetNavChildren(parentEntityKey, navProp, true);
   navChildren.Add(child);
 
 }
        /// <summary>
        /// Creates an AssociationAttribute for the specified navigation property
        /// </summary>
        /// <param name="navigationProperty">The navigation property that corresponds to the association (it identifies the end points)</param>
        /// <returns>A new AssociationAttribute that describes the given navigation property association</returns>
        internal AssociationAttribute CreateAssociationAttribute(NavigationProperty navigationProperty)
        {
            AssociationInfo assocInfo = this.GetAssociationInfo(navigationProperty);
            bool isForeignKey = navigationProperty.FromEndMember.Name == assocInfo.FKRole;
            string thisKey;
            string otherKey;
            if (isForeignKey)
            {
                thisKey = FormatMemberList(assocInfo.ThisKey);
                otherKey = FormatMemberList(assocInfo.OtherKey);
            }
            else
            {
                otherKey = FormatMemberList(assocInfo.ThisKey);
                thisKey = FormatMemberList(assocInfo.OtherKey);
            }

            AssociationAttribute assocAttrib = new AssociationAttribute(assocInfo.Name, thisKey, otherKey);
            assocAttrib.IsForeignKey = isForeignKey;
            return assocAttrib;
        }
 internal NavigationPropertyAdd(NavigationProperty property)
 {
     _property = property;
 }
Ejemplo n.º 47
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="reader"></param>
 private void HandleNavigationPropertyElement(XmlReader reader)
 {
     NavigationProperty navigationProperty = new NavigationProperty(this);
     navigationProperty.Parse(reader);
     AddMember(navigationProperty);
 }