public IEntityWrapper HandleRelationshipSpan( IEntityWrapper wrappedEntity, EntityKey targetKey, AssociationEndMember targetMember) { if (wrappedEntity.Entity == null) { return(wrappedEntity); } EntityKey entityKey = wrappedEntity.EntityKey; AssociationEndMember otherAssociationEnd = MetadataHelper.GetOtherAssociationEnd(targetMember); this.CheckClearedEntryOnSpan((object)targetKey, wrappedEntity, entityKey, targetMember); if ((object)targetKey != null) { EntitySet endEntitySet; AssociationSet cspaceAssociationSet = this.Context.MetadataWorkspace.MetadataOptimization.FindCSpaceAssociationSet((AssociationType)targetMember.DeclaringType, targetMember.Name, targetKey.EntitySetName, targetKey.EntityContainerName, out endEntitySet); ObjectStateManager objectStateManager = this.Context.ObjectStateManager; EntityState newEntryState; if (!ObjectStateManager.TryUpdateExistingRelationships(this.Context, this.MergeOption, cspaceAssociationSet, otherAssociationEnd, entityKey, wrappedEntity, targetMember, targetKey, true, out newEntryState)) { EntityEntry entityEntry = objectStateManager.GetOrAddKeyEntry(targetKey, endEntitySet); bool flag = true; switch (otherAssociationEnd.RelationshipMultiplicity) { case RelationshipMultiplicity.ZeroOrOne: case RelationshipMultiplicity.One: flag = !ObjectStateManager.TryUpdateExistingRelationships(this.Context, this.MergeOption, cspaceAssociationSet, targetMember, targetKey, entityEntry.WrappedEntity, otherAssociationEnd, entityKey, true, out newEntryState); if (entityEntry.State == EntityState.Detached) { entityEntry = objectStateManager.AddKeyEntry(targetKey, endEntitySet); break; } break; } if (flag) { if (entityEntry.IsKeyEntry || newEntryState == EntityState.Deleted) { RelationshipWrapper wrapper = new RelationshipWrapper(cspaceAssociationSet, otherAssociationEnd.Name, entityKey, targetMember.Name, targetKey); objectStateManager.AddNewRelation(wrapper, newEntryState); } else if (entityEntry.State != EntityState.Deleted) { ObjectStateManager.AddEntityToCollectionOrReference(this.MergeOption, wrappedEntity, otherAssociationEnd, entityEntry.WrappedEntity, targetMember, true, false, false); } else { RelationshipWrapper wrapper = new RelationshipWrapper(cspaceAssociationSet, otherAssociationEnd.Name, entityKey, targetMember.Name, targetKey); objectStateManager.AddNewRelation(wrapper, EntityState.Deleted); } } } } else { RelatedEnd relatedEnd; if (this.TryGetRelatedEnd(wrappedEntity, (AssociationType)targetMember.DeclaringType, otherAssociationEnd.Name, targetMember.Name, out relatedEnd)) { this.SetIsLoadedForSpan(relatedEnd, false); } } return(wrappedEntity); }