Beispiel #1
0
        protected override void OnDataBinding(EventArgs e)
        {
            base.OnDataBinding(e);

            object entity;
            ICustomTypeDescriptor rowDescriptor = Row as ICustomTypeDescriptor;

            if (rowDescriptor != null)
            {
                // Get the real entity from the wrapper
                entity = rowDescriptor.GetPropertyOwner(null);
            }
            else
            {
                entity = Row;
            }

            // Get the collection and make sure it's loaded
            RelatedEnd entityCollection = Column.EntityTypeProperty.GetValue(entity, null) as RelatedEnd;

            if (entityCollection == null)
            {
                throw new InvalidOperationException(String.Format("The ManyToMany template does not support the collection type of the '{0}' column on the '{1}' table.", Column.Name, Table.Name));
            }
            if (!entityCollection.IsLoaded)
            {
                entityCollection.Load();
            }

            // Bind the repeater to the list of children entities
            Repeater1.DataSource = entityCollection;
            Repeater1.DataBind();
        }
Beispiel #2
0
        /// <summary>
        /// Method called by proxy interceptor delegate to provide lazy loading behavior for navigation properties.
        /// </summary>
        /// <typeparam name="TItem">property type</typeparam>
        /// <param name="propertyValue">The property value whose associated relationship is to be loaded.</param>
        /// <param name="relationshipName">String name of the relationship.</param>
        /// <param name="targetRoleName">String name of the related end to be loaded for the relationship specified by <paramref name="relationshipName"/>.</param>
        /// <param name="wrapperObject">Entity wrapper object used to retrieve RelationshipManager for the proxied entity.</param>
        /// <returns>
        /// True if the value instance was mutated and can be returned
        /// False if the class should refetch the value because the instance has changed
        /// </returns>
        private static bool LoadProperty <TItem>(TItem propertyValue, string relationshipName, string targetRoleName, bool mustBeNull, object wrapperObject) where TItem : class
        {
            // Only attempt to load collection if:
            //
            // 1. Collection is non-null.
            // 2. ObjectContext.ContextOptions.LazyLoadingEnabled is true
            // 3. A non-null RelationshipManager can be retrieved (this is asserted).
            // 4. The EntityCollection is not already loaded.

            Debug.Assert(wrapperObject == null || wrapperObject is IEntityWrapper, "wrapperObject must be an IEntityWrapper");
            IEntityWrapper wrapper = (IEntityWrapper)wrapperObject; // We want an exception if the cast fails.

            if (wrapper != null && wrapper.Context != null)
            {
                RelationshipManager relationshipManager = wrapper.RelationshipManager;
                Debug.Assert(relationshipManager != null, "relationshipManager should be non-null");
                if (relationshipManager != null && (!mustBeNull || propertyValue == null))
                {
                    RelatedEnd relatedEnd = relationshipManager.GetRelatedEndInternal(relationshipName, targetRoleName);
                    relatedEnd.DeferredLoad();
                }
            }

            return(propertyValue != null);
        }
Beispiel #3
0
        protected override void OnDataBinding(EventArgs e)
        {
            base.OnDataBinding(e);

            object entity;
            ICustomTypeDescriptor rowDescriptor = Row as ICustomTypeDescriptor;

            if (rowDescriptor != null)
            {
                // 从包装中获取实际实体
                entity = rowDescriptor.GetPropertyOwner(null);
            }
            else
            {
                entity = Row;
            }

            // 获取集合并确保加载它
            RelatedEnd entityCollection = Column.EntityTypeProperty.GetValue(entity, null) as RelatedEnd;

            if (entityCollection == null)
            {
                throw new InvalidOperationException(String.Format("ManyToMany 模板不支持 '{1}' 表上的 '{0}' 列的集合类型。", Column.Name, Table.Name));
            }
            if (!entityCollection.IsLoaded)
            {
                entityCollection.Load();
            }

            // 将 Repeater 绑定到子实体的列表中
            Repeater1.DataSource = entityCollection;
            Repeater1.DataBind();
        }
 public void SetNavigationPropertyValue(RelatedEnd relatedEnd, object value)
 {
     if (relatedEnd == null)
     {
         return;
     }
     if (relatedEnd.TargetAccessor.ValueSetter == null)
     {
         Type         declaringType = PocoPropertyAccessorStrategy.GetDeclaringType(relatedEnd);
         PropertyInfo topProperty   = declaringType.GetTopProperty(relatedEnd.TargetAccessor.PropertyName);
         if (topProperty == (PropertyInfo)null)
         {
             throw new EntityException(Strings.PocoEntityWrapper_UnableToSetFieldOrProperty((object)relatedEnd.TargetAccessor.PropertyName, (object)declaringType.FullName));
         }
         EntityProxyFactory entityProxyFactory = new EntityProxyFactory();
         relatedEnd.TargetAccessor.ValueSetter = entityProxyFactory.CreateBaseSetter(topProperty.DeclaringType, topProperty);
     }
     try
     {
         relatedEnd.TargetAccessor.ValueSetter(this._entity, value);
     }
     catch (Exception ex)
     {
         throw new EntityException(Strings.PocoEntityWrapper_UnableToSetFieldOrProperty((object)relatedEnd.TargetAccessor.PropertyName, (object)this._entity.GetType().FullName), ex);
     }
 }
Beispiel #5
0
        protected override void OnDataBinding(EventArgs e)
        {
            base.OnDataBinding(e);

            object entity;
            ICustomTypeDescriptor rowDescriptor = Row as ICustomTypeDescriptor;

            if (rowDescriptor != null)
            {
                // Obtener la entidad real del contenedor
                entity = rowDescriptor.GetPropertyOwner(null);
            }
            else
            {
                entity = Row;
            }

            // Obtener la colección y asegurarse de que se ha cargado
            RelatedEnd entityCollection = Column.EntityTypeProperty.GetValue(entity, null) as RelatedEnd;

            if (entityCollection == null)
            {
                throw new InvalidOperationException(String.Format("La plantilla ManyToMany no admite el tipo de colección de la columna '{0}' en la tabla '{1}'.", Column.Name, Table.Name));
            }
            if (!entityCollection.IsLoaded)
            {
                entityCollection.Load();
            }

            // Enlazar el control repeater a la lista de entidades secundarias
            Repeater1.DataSource = entityCollection;
            Repeater1.DataBind();
        }
        public bool CollectionRemove(RelatedEnd relatedEnd, object value)
        {
            object entity = this._entity;

            try
            {
                object navigationPropertyValue = this.GetNavigationPropertyValue(relatedEnd);
                if (navigationPropertyValue != null)
                {
                    if (object.ReferenceEquals(navigationPropertyValue, (object)relatedEnd))
                    {
                        return(true);
                    }
                    if (relatedEnd.TargetAccessor.CollectionRemove == null)
                    {
                        relatedEnd.TargetAccessor.CollectionRemove = PocoPropertyAccessorStrategy.CreateCollectionRemoveFunction(PocoPropertyAccessorStrategy.GetDeclaringType(relatedEnd), relatedEnd.TargetAccessor.PropertyName);
                    }
                    return(relatedEnd.TargetAccessor.CollectionRemove(navigationPropertyValue, value));
                }
            }
            catch (Exception ex)
            {
                throw new EntityException(Strings.PocoEntityWrapper_UnableToSetFieldOrProperty((object)relatedEnd.TargetAccessor.PropertyName, (object)entity.GetType().FullName), ex);
            }
            return(false);
        }
        public object GetNavigationPropertyValue(RelatedEnd relatedEnd)
        {
            object obj = (object)null;

            if (relatedEnd != null)
            {
                if (relatedEnd.TargetAccessor.ValueGetter == null)
                {
                    Type         declaringType = PocoPropertyAccessorStrategy.GetDeclaringType(relatedEnd);
                    PropertyInfo topProperty   = declaringType.GetTopProperty(relatedEnd.TargetAccessor.PropertyName);
                    if (topProperty == (PropertyInfo)null)
                    {
                        throw new EntityException(Strings.PocoEntityWrapper_UnableToSetFieldOrProperty((object)relatedEnd.TargetAccessor.PropertyName, (object)declaringType.FullName));
                    }
                    EntityProxyFactory entityProxyFactory = new EntityProxyFactory();
                    relatedEnd.TargetAccessor.ValueGetter = entityProxyFactory.CreateBaseGetter(topProperty.DeclaringType, topProperty);
                }
                bool state = relatedEnd.DisableLazyLoading();
                try
                {
                    obj = relatedEnd.TargetAccessor.ValueGetter(this._entity);
                }
                catch (Exception ex)
                {
                    throw new EntityException(Strings.PocoEntityWrapper_UnableToSetFieldOrProperty((object)relatedEnd.TargetAccessor.PropertyName, (object)this._entity.GetType().FullName), ex);
                }
                finally
                {
                    relatedEnd.ResetLazyLoading(state);
                }
            }
            return(obj);
        }
        private void IncludeEntityKey(bool doAttach)
        {
            ObjectStateManager objectStateManager = this.ObjectContext.ObjectStateManager;
            bool        flag1       = false;
            bool        flag2       = false;
            EntityEntry entityEntry = objectStateManager.FindEntityEntry(this.DetachedEntityKey);

            if (entityEntry == null)
            {
                flag2 = true;
                flag1 = true;
            }
            else if (entityEntry.IsKeyEntry)
            {
                if (this.FromEndMember.RelationshipMultiplicity != RelationshipMultiplicity.Many)
                {
                    foreach (RelationshipEntry relationshipEntry in this.ObjectContext.ObjectStateManager.FindRelationshipsByKey(this.DetachedEntityKey))
                    {
                        if (relationshipEntry.IsSameAssociationSetAndRole((AssociationSet)this.RelationshipSet, (AssociationEndMember)this.ToEndMember, this.DetachedEntityKey) && relationshipEntry.State != EntityState.Deleted)
                        {
                            throw new InvalidOperationException(Strings.ObjectStateManager_EntityConflictsWithKeyEntry);
                        }
                    }
                }
                flag1 = true;
            }
            else
            {
                IEntityWrapper wrappedEntity = entityEntry.WrappedEntity;
                if (entityEntry.State == EntityState.Deleted)
                {
                    throw new InvalidOperationException(Strings.RelatedEnd_UnableToAddRelationshipWithDeletedEntity);
                }
                RelatedEnd relatedEndInternal = wrappedEntity.RelationshipManager.GetRelatedEndInternal(this.RelationshipName, this.RelationshipNavigation.From);
                if (this.FromEndMember.RelationshipMultiplicity != RelationshipMultiplicity.Many && !relatedEndInternal.IsEmpty())
                {
                    throw new InvalidOperationException(Strings.ObjectStateManager_EntityConflictsWithKeyEntry);
                }
                this.Add(wrappedEntity, true, doAttach, false, true, true);
                objectStateManager.TransactionManager.PopulatedEntityReferences.Add((EntityReference)this);
            }
            if (!flag1 || this.IsForeignKey)
            {
                return;
            }
            if (flag2)
            {
                EntitySet entitySet = this.DetachedEntityKey.GetEntitySet(this.ObjectContext.MetadataWorkspace);
                objectStateManager.AddKeyEntry(this.DetachedEntityKey, entitySet);
            }
            EntityKey entityKey = this.WrappedOwner.EntityKey;

            if ((object)entityKey == null)
            {
                throw Error.EntityKey_UnexpectedNull();
            }
            RelationshipWrapper wrapper = new RelationshipWrapper((AssociationSet)this.RelationshipSet, this.RelationshipNavigation.From, entityKey, this.RelationshipNavigation.To, this.DetachedEntityKey);

            objectStateManager.AddNewRelation(wrapper, doAttach ? EntityState.Unchanged : EntityState.Added);
        }
Beispiel #9
0
        // <summary>
        // Sets the IsLoaded flag to "true"
        // There are also rules for when this can be set based on MergeOption and the current value(s) in the related end.
        // </summary>
        private void SetIsLoadedForSpan(RelatedEnd relatedEnd, bool forceToTrue)
        {
            DebugCheck.NotNull(relatedEnd);

            // We can now say this related end is "Loaded"
            // The cases where we should set this to true are:
            // AppendOnly: the related end is empty and does not point to a stub
            // PreserveChanges: the related end is empty and does not point to a stub (otherwise, an Added item exists and IsLoaded should not change)
            // OverwriteChanges: always
            // NoTracking: always
            if (!forceToTrue)
            {
                // Detect the empty value state of the relatedEnd
                forceToTrue = relatedEnd.IsEmpty();
                var reference = relatedEnd as EntityReference;
                if (reference != null)
                {
                    forceToTrue &= reference.EntityKey == null;
                }
            }
            if (forceToTrue || MergeOption == MergeOption.OverwriteChanges)
            {
                relatedEnd.IsLoaded = true;
            }
        }
        // See IPropertyAccessorStrategy
        public void CollectionAdd(RelatedEnd relatedEnd, object value)
        {
            object entity = _entity;

            try
            {
                object collection = GetNavigationPropertyValue(relatedEnd);
                if (collection == null)
                {
                    collection = CollectionCreate(relatedEnd);
                    SetNavigationPropertyValue(relatedEnd, collection);
                }
                Debug.Assert(collection != null, "Collection is null");

                // do not call Add if the collection is a RelatedEnd instance
                if (collection == relatedEnd)
                {
                    return;
                }

                if (relatedEnd.TargetAccessor.CollectionAdd == null)
                {
                    relatedEnd.TargetAccessor.CollectionAdd = CreateCollectionAddFunction(entity.GetType(), relatedEnd.TargetAccessor.PropertyName);
                }


                relatedEnd.TargetAccessor.CollectionAdd(collection, value);
            }
            catch (Exception ex)
            {
                throw new EntityException(System.Data.Entity.Strings.PocoEntityWrapper_UnableToSetFieldOrProperty(relatedEnd.TargetAccessor.PropertyName, entity.GetType().FullName), ex);
            }
        }
        // See IPropertyAccessorStrategy
        public object GetNavigationPropertyValue(RelatedEnd relatedEnd)
        {
            object navPropValue = null;

            if (relatedEnd != null)
            {
                if (relatedEnd.TargetAccessor.ValueGetter == null)
                {
                    Type         type         = GetDeclaringType(relatedEnd);
                    PropertyInfo propertyInfo = EntityUtil.GetTopProperty(ref type, relatedEnd.TargetAccessor.PropertyName);
                    if (propertyInfo == null)
                    {
                        throw new EntityException(System.Data.Entity.Strings.PocoEntityWrapper_UnableToSetFieldOrProperty(relatedEnd.TargetAccessor.PropertyName, type.FullName));
                    }
                    EntityProxyFactory factory = new EntityProxyFactory();
                    relatedEnd.TargetAccessor.ValueGetter = factory.CreateBaseGetter(type, propertyInfo);
                }
                try
                {
                    navPropValue = relatedEnd.TargetAccessor.ValueGetter(_entity);
                }
                catch (Exception ex)
                {
                    throw new EntityException(System.Data.Entity.Strings.PocoEntityWrapper_UnableToSetFieldOrProperty(relatedEnd.TargetAccessor.PropertyName, _entity.GetType().FullName), ex);
                }
            }
            return(navPropValue);
        }
Beispiel #12
0
 // See IEntityWrapper documentation
 public override void SetNavigationPropertyValue(RelatedEnd relatedEnd, object value)
 {
     if (_propertyStrategy != null)
     {
         _propertyStrategy.SetNavigationPropertyValue(relatedEnd, value);
     }
 }
        // See IPropertyAccessorStrategy
        public bool CollectionRemove(RelatedEnd relatedEnd, object value)
        {
            var entity = _entity;

            try
            {
                var collection = GetNavigationPropertyValue(relatedEnd);
                if (collection != null)
                {
                    // do not call Add if the collection is a RelatedEnd instance
                    if (ReferenceEquals(collection, relatedEnd))
                    {
                        return(true);
                    }

                    if (relatedEnd.TargetAccessor.CollectionRemove == null)
                    {
                        relatedEnd.TargetAccessor.CollectionRemove = CreateCollectionRemoveFunction(
                            GetDeclaringType(relatedEnd), relatedEnd.TargetAccessor.PropertyName);
                    }

                    return(relatedEnd.TargetAccessor.CollectionRemove(collection, value));
                }
            }
            catch (Exception ex)
            {
                throw new EntityException(
                          Strings.PocoEntityWrapper_UnableToSetFieldOrProperty(relatedEnd.TargetAccessor.PropertyName, entity.GetType().FullName),
                          ex);
            }
            return(false);
        }
Beispiel #14
0
        protected override void OnDataBinding(EventArgs e)
        {
            base.OnDataBinding(e);

            object entity;
            ICustomTypeDescriptor rowDescriptor = Row as ICustomTypeDescriptor;

            if (rowDescriptor != null)
            {
                // 從包裝函式取得真正的實體
                entity = rowDescriptor.GetPropertyOwner(null);
            }
            else
            {
                entity = Row;
            }

            // 取得集合並確認它已被載入
            RelatedEnd entityCollection = Column.EntityTypeProperty.GetValue(entity, null) as RelatedEnd;

            if (entityCollection == null)
            {
                throw new InvalidOperationException(String.Format("ManyToMany 範本不支援 '{1}' 資料表的 '{0}' 資料行的集合型別。", Column.Name, Table.Name));
            }
            if (!entityCollection.IsLoaded)
            {
                entityCollection.Load();
            }

            // 將重複項繫結至子實體清單
            Repeater1.DataSource = entityCollection;
            Repeater1.DataBind();
        }
Beispiel #15
0
        internal override bool CheckReferentialConstraintPrincipalProperty(
            EntityEntry ownerEntry,
            ReferentialConstraint constraint)
        {
            EntityKey principalKey;

            if (!this.IsEmpty())
            {
                IEntityWrapper referenceValue = this.ReferenceValue;
                if (referenceValue.ObjectStateEntry != null && referenceValue.ObjectStateEntry.State == EntityState.Added)
                {
                    return(true);
                }
                principalKey = this.ExtractPrincipalKey(referenceValue);
            }
            else
            {
                if (this.ToEndMember.RelationshipMultiplicity != RelationshipMultiplicity.ZeroOrOne && this.ToEndMember.RelationshipMultiplicity != RelationshipMultiplicity.One || !(this.DetachedEntityKey != (EntityKey)null))
                {
                    return(true);
                }
                principalKey = !this.IsForeignKey || this.ObjectContext.ObjectStateManager.TransactionManager.IsAddTracking || this.ObjectContext.ObjectStateManager.TransactionManager.IsAttachTracking ? this.DetachedEntityKey : this.EntityKey;
            }
            return(RelatedEnd.VerifyRIConstraintsWithRelatedEntry(constraint, new Func <string, object>(ownerEntry.GetCurrentEntityValue), principalKey));
        }
 // See IPropertyAccessorStrategy
 public void SetNavigationPropertyValue(RelatedEnd relatedEnd, object value)
 {
     if (relatedEnd != null)
     {
         if (relatedEnd.TargetAccessor.ValueSetter == null)
         {
             var type         = GetDeclaringType(relatedEnd);
             var propertyInfo = type.GetTopProperty(relatedEnd.TargetAccessor.PropertyName);
             if (propertyInfo == null)
             {
                 throw new EntityException(
                           Strings.PocoEntityWrapper_UnableToSetFieldOrProperty(relatedEnd.TargetAccessor.PropertyName, type.FullName));
             }
             var factory = new EntityProxyFactory();
             relatedEnd.TargetAccessor.ValueSetter = factory.CreateBaseSetter(propertyInfo.DeclaringType, propertyInfo);
         }
         try
         {
             relatedEnd.TargetAccessor.ValueSetter(_entity, value);
         }
         catch (Exception ex)
         {
             throw new EntityException(
                       Strings.PocoEntityWrapper_UnableToSetFieldOrProperty(
                           relatedEnd.TargetAccessor.PropertyName, _entity.GetType().FullName), ex);
         }
     }
 }
Beispiel #17
0
 public override void CollectionAdd(RelatedEnd relatedEnd, object value)
 {
     if (_propertyStrategy != null)
     {
         _propertyStrategy.CollectionAdd(relatedEnd, value);
     }
 }
Beispiel #18
0
 public static void EnsureLoaded(this RelatedEnd relatedEnd)
 {
     if (!relatedEnd.IsLoaded)
     {
         relatedEnd.Load();
     }
 }
Beispiel #19
0
 public static void LoadOnce(this RelatedEnd entity)
 {
     if (!entity.IsLoaded)
     {
         entity.Load();
     }
 }
 /// <summary>
 /// Creates an EntityKey for a principal entity based on the foreign key values contained
 /// in this entity.  This implies that this entity is at the dependent end of the relationship.
 /// </summary>
 /// <param name="dependentEntry">The EntityEntry for the dependent that contains the FK</param>
 /// <param name="relatedEnd">Identifies the principal end for which a key is required</param>
 /// <returns>The key, or null if any value in the key is null</returns>
 public static EntityKey CreateKeyFromForeignKeyValues(EntityEntry dependentEntry, RelatedEnd relatedEnd)
 {
     // Note: there is only ever one constraint per association type
     ReferentialConstraint constraint = ((AssociationType)relatedEnd.RelationMetadata).ReferentialConstraints.First();
     Debug.Assert(constraint.FromRole.Identity == relatedEnd.TargetRoleName, "Unexpected constraint role");
     return CreateKeyFromForeignKeyValues(dependentEntry, constraint, relatedEnd.GetTargetEntitySetFromRelationshipSet(), useOriginalValues: false);
 }
Beispiel #21
0
 public override void CollectionAdd(RelatedEnd relatedEnd, object value)
 {
     if (this._propertyStrategy == null)
     {
         return;
     }
     this._propertyStrategy.CollectionAdd(relatedEnd, value);
 }
 private static Type GetDeclaringType(RelatedEnd relatedEnd)
 {
     if (relatedEnd.NavigationProperty != null)
     {
         return(Util.GetObjectMapping((EdmType)relatedEnd.NavigationProperty.DeclaringType, relatedEnd.WrappedOwner.Context.MetadataWorkspace).ClrType.ClrType);
     }
     return(relatedEnd.WrappedOwner.IdentityType);
 }
Beispiel #23
0
 public override bool CollectionRemove(RelatedEnd relatedEnd, object value)
 {
     if (this._propertyStrategy == null)
     {
         return(false);
     }
     return(this._propertyStrategy.CollectionRemove(relatedEnd, value));
 }
Beispiel #24
0
 public override void SetNavigationPropertyValue(RelatedEnd relatedEnd, object value)
 {
     if (this._propertyStrategy == null)
     {
         return;
     }
     this._propertyStrategy.SetNavigationPropertyValue(relatedEnd, value);
 }
Beispiel #25
0
 public override void RemoveNavigationPropertyValue(RelatedEnd relatedEnd, object value)
 {
     if (this._propertyStrategy == null || !object.ReferenceEquals(this._propertyStrategy.GetNavigationPropertyValue(relatedEnd), value))
     {
         return;
     }
     this._propertyStrategy.SetNavigationPropertyValue(relatedEnd, (object)null);
 }
Beispiel #26
0
        public static EntityKey CreateKeyFromForeignKeyValues(
            EntityEntry dependentEntry,
            RelatedEnd relatedEnd)
        {
            ReferentialConstraint constraint = ((AssociationType)relatedEnd.RelationMetadata).ReferentialConstraints.First <ReferentialConstraint>();

            return(ForeignKeyFactory.CreateKeyFromForeignKeyValues(dependentEntry, constraint, relatedEnd.GetTargetEntitySetFromRelationshipSet(), false));
        }
Beispiel #27
0
 public override object GetNavigationPropertyValue(RelatedEnd relatedEnd)
 {
     if (this._propertyStrategy == null)
     {
         return((object)null);
     }
     return(this._propertyStrategy.GetNavigationPropertyValue(relatedEnd));
 }
        protected internal override IEnumerable GetDetailsForParentItem(DataGridCollectionViewBase parentCollectionView, object parentItem)
        {
            EntityObject entityObject = parentItem as EntityObject;

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

            // Even if EntityObject is not in a loadable state, we must still return the IList
            // so that the ItemProperties can be extracted based on the elements type.
            bool entityObjectLoadable = ItemsSourceHelper.IsEntityObjectLoadable(entityObject);

            // We let the user take charge of handling the details.
            QueryEntityDetailsEventArgs args = new QueryEntityDetailsEventArgs(entityObject);

            if (entityObjectLoadable)
            {
                this.OnQueryDetails(args);
            }

            // The parentItem must implement IEntityWithRelationships
            Type parentItemType = parentItem.GetType();

            if (typeof(IEntityWithRelationships).IsAssignableFrom(parentItemType))
            {
                // Since the relationship was based on the the property
                // name, we must find that property using reflection.
                PropertyInfo propertyInfo = parentItemType.GetProperty(this.RelationName);

                if (propertyInfo != null)
                {
                    RelatedEnd relatedEnd = propertyInfo.GetValue(parentItem, null) as RelatedEnd;

                    if (relatedEnd != null)
                    {
                        // Make sure that the details are loaded
                        // except if the user already handled it.
                        if (!relatedEnd.IsLoaded &&
                            !args.Handled &&
                            entityObjectLoadable)
                        {
                            relatedEnd.Load();
                        }

                        IListSource listSource = relatedEnd as IListSource;

                        // Returns an IList to have proper change notification events.
                        if (listSource != null)
                        {
                            return(listSource.GetList());
                        }
                    }
                }
            }

            return(null);
        }
Beispiel #29
0
        public override void EnsureCollectionNotNull(RelatedEnd relatedEnd)
        {
            if (this._propertyStrategy == null || this._propertyStrategy.GetNavigationPropertyValue(relatedEnd) != null)
            {
                return;
            }
            object obj = this._propertyStrategy.CollectionCreate(relatedEnd);

            this._propertyStrategy.SetNavigationPropertyValue(relatedEnd, obj);
        }
        /// <summary>
        ///     Gets the navigation property value from the <see cref="IRelatedEnd" /> object.
        ///     For reference navigation properties, this means getting the value from the
        ///     <see cref="EntityReference{T}" /> object.
        /// </summary>
        /// <param name="entity"> The entity. </param>
        /// <returns> The navigation property value. </returns>
        protected override object GetNavigationPropertyFromRelatedEnd(object entity)
        {
            Debug.Assert(!(RelatedEnd is IDisposable), "RelatedEnd is not expected to be disposable.");

            // To avoid needing to access the generic EntityReference<T> class we instead
            // treat the RelatedEnd as an IEnumerable and get the single value that way.
            var enumerator = RelatedEnd.GetEnumerator();

            return(enumerator.MoveNext() ? enumerator.Current : null);
        }
        internal void InitializeWithValue(RelatedEnd relatedEnd)
        {
            EntityReference <TEntity> entityReference = relatedEnd as EntityReference <TEntity>;

            if (entityReference == null || entityReference._wrappedCachedValue.Entity == null)
            {
                return;
            }
            this._wrappedCachedValue = entityReference._wrappedCachedValue;
            this._cachedValue        = (TEntity)this._wrappedCachedValue.Entity;
        }
 public void CollectionAdd(RelatedEnd relatedEnd, object value)
 {
     Debug.Fail("Cannot modify collection from null wrapper.");
 }
 public void EnsureCollectionNotNull(RelatedEnd relatedEnd)
 {
     Debug.Fail("Cannot modify collection from null wrapper.");
 }
 public object GetNavigationPropertyValue(RelatedEnd relatedEnd)
 {
     Debug.Fail("Cannot access property using null wrapper.");
     return null;
 }
        internal void ChangeRelationshipState(EntityEntry targetEntry, RelatedEnd relatedEnd, EntityState requestedState)
        {
            Debug.Assert(requestedState != EntityState.Modified, "Invalid requested state for relationsihp");
            Debug.Assert(State != EntityState.Modified, "Invalid initial state for relationsihp");

            var initialState = State;

            switch (initialState)
            {
                case EntityState.Added:
                    switch (requestedState)
                    {
                        case EntityState.Added:
                            // no-op
                            break;
                        case EntityState.Unchanged:
                            AcceptChanges();
                            break;
                        case EntityState.Deleted:
                            AcceptChanges();
                            // cascade deletion is not performed because TransactionManager.IsLocalPublicAPI == true
                            Delete();
                            break;
                        case EntityState.Detached:
                            // cascade deletion is not performed because TransactionManager.IsLocalPublicAPI == true
                            Delete();
                            break;
                        default:
                            Debug.Assert(false, "Invalid requested state");
                            break;
                    }
                    break;
                case EntityState.Unchanged:
                    switch (requestedState)
                    {
                        case EntityState.Added:
                            ObjectStateManager.ChangeState(this, EntityState.Unchanged, EntityState.Added);
                            State = EntityState.Added;
                            break;
                        case EntityState.Unchanged:
                            //no-op
                            break;
                        case EntityState.Deleted:
                            // cascade deletion is not performed because TransactionManager.IsLocalPublicAPI == true
                            Delete();
                            break;
                        case EntityState.Detached:
                            // cascade deletion is not performed because TransactionManager.IsLocalPublicAPI == true
                            Delete();
                            AcceptChanges();
                            break;
                        default:
                            Debug.Assert(false, "Invalid requested state");
                            break;
                    }
                    break;
                case EntityState.Deleted:
                    switch (requestedState)
                    {
                        case EntityState.Added:
                            relatedEnd.Add(
                                targetEntry.WrappedEntity,
                                applyConstraints: true,
                                addRelationshipAsUnchanged: false,
                                relationshipAlreadyExists: true,
                                allowModifyingOtherEndOfRelationship: false,
                                forceForeignKeyChanges: true);
                            ObjectStateManager.ChangeState(this, EntityState.Deleted, EntityState.Added);
                            State = EntityState.Added;
                            break;
                        case EntityState.Unchanged:
                            relatedEnd.Add(
                                targetEntry.WrappedEntity,
                                applyConstraints: true,
                                addRelationshipAsUnchanged: false,
                                relationshipAlreadyExists: true,
                                allowModifyingOtherEndOfRelationship: false,
                                forceForeignKeyChanges: true);
                            ObjectStateManager.ChangeState(this, EntityState.Deleted, EntityState.Unchanged);
                            State = EntityState.Unchanged;
                            break;
                        case EntityState.Deleted:
                            // no-op
                            break;
                        case EntityState.Detached:
                            AcceptChanges();
                            break;
                        default:
                            Debug.Assert(false, "Invalid requested state");
                            break;
                    }
                    break;
                default:
                    Debug.Assert(false, "Invalid entry state");
                    break;
            }
        }
        protected override bool UpdateDependentEndForeignKey(RelatedEnd targetRelatedEnd, bool forceForeignKeyChanges)
        {
            if (IsDependentEndOfReferentialConstraint(false))
            {
                UpdateForeignKeyValues(WrappedOwner, targetRelatedEnd.WrappedOwner, changedFKs: null, forceChange: forceForeignKeyChanges);

                return true;
            }
            return false;
        }
        protected override void AddToNavigationPropertyIfCompatible(RelatedEnd otherRelatedEnd)
        {
            // If this end is non-null, then don't overwrite it.
            // If it's non-null and doesn't match what we think it should be, then throw.
            if (NavigationPropertyIsNullOrMissing())
            {
                AddToNavigationProperty(otherRelatedEnd.WrappedOwner);
                // If the other end is a dependent that is already tracked, then we need to make sure
                // its FK props are marked as modified even though we are not fixing them up.
                Debug.Assert(otherRelatedEnd.ObjectContext != null, "Expected attached context at this point.");

                var cacheEntry = otherRelatedEnd.ObjectContext.ObjectStateManager.FindEntityEntry(otherRelatedEnd.WrappedOwner.Entity);

                if (cacheEntry != null &&
                    otherRelatedEnd.ObjectContext.ObjectStateManager.TransactionManager.IsAddTracking &&
                    otherRelatedEnd.IsForeignKey
                    &&
                    IsDependentEndOfReferentialConstraint(checkIdentifying: false))
                {
                    MarkForeignKeyPropertiesModified();
                }
            }
            else if (!CheckIfNavigationPropertyContainsEntity(otherRelatedEnd.WrappedOwner))
            {
                throw Error.ObjectStateManager_ConflictingChangesOfRelationshipDetected(
                    RelationshipNavigation.To,
                    RelationshipNavigation.RelationshipName);
            }
        }
 public void RemoveNavigationPropertyValue(RelatedEnd relatedEnd, object value)
 {
     Debug.Fail("Cannot access property using null wrapper.");
 }
 public bool CollectionRemove(RelatedEnd relatedEnd, object value)
 {
     Debug.Fail("Cannot modify collection from null wrapper.");
     return false;
 }