entity-frameworklazy-loadingnavigation-propertiesentityreference

Is EntityReference.Load checking for EntityReference.IsLoaded?


Hi I was wondering if EntityReference.Load method includes

If Not ref.IsLoaded Then ref.Load()

My question is basically:

Dim person = Context.Persons.FirstOrDefault
person.AddressReference.Load()
person.AddressReference.Load() 'Does it do anything?

Solution

  • It does Load again. I verified this by Profiler and it shown two queries. Default merge option is MergeOption.AppendOnly and it doesn't prevent from querying again. Code from Reflector:

    public override void Load(MergeOption mergeOption)
    {
        base.CheckOwnerNull();
        ObjectQuery<TEntity> query = base.ValidateLoad<TEntity>(mergeOption, "EntityReference");
        base._suppressEvents = true;
        try
        {
            List<TEntity> collection = new List<TEntity>(RelatedEnd.GetResults<TEntity>(query));
            if (collection.Count > 1)
            {
                throw EntityUtil.MoreThanExpectedRelatedEntitiesFound();
            }
            if (collection.Count == 0)
            {
                if (base.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.One)
                {
                    throw EntityUtil.LessThanExpectedRelatedEntitiesFound();
                }
                if ((mergeOption == MergeOption.OverwriteChanges) || (mergeOption == MergeOption.PreserveChanges))
                {
                    EntityKey entityKey = ObjectStateManager.FindKeyOnEntityWithRelationships(base.Owner);
                    EntityUtil.CheckEntityKeyNull(entityKey);
                    ObjectStateManager.RemoveRelationships(base.ObjectContext, mergeOption, (AssociationSet) base.RelationshipSet, entityKey, (AssociationEndMember) base.FromEndProperty);
                }
                base._isLoaded = true;
            }
            else
            {
                base.Merge<TEntity>(collection, mergeOption, true);
            }
        }
        finally
        {
            base._suppressEvents = false;
        }
        this.OnAssociationChanged(CollectionChangeAction.Refresh, null);
    }