Question

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?
Was it helpful?

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);
}

OTHER TIPS

Just for reference for anyone else finding the accepted answer, here is the extension method I created for my current project.

using System.Data.Objects.DataClasses;

namespace ProjectName
{
    public static class EntityFrameworkExtensions
    {
        public static void EnsureLoaded<TEntity>(this EntityReference<TEntity> reference)
            where TEntity : class, IEntityWithRelationships
        {
            if (!reference.IsLoaded)
                reference.Load();
        }
    }
}

And usage:

Patient patient = // get patient

patient.ClinicReference.EnsureLoaded();
patient.Clinic.DoStuff();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top