default
default

Reputation: 11635

Check if navigational property is loaded

Is it possible to check if a navigational property has been loaded? When I try to access it I only get an ObjectDisposedException

The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

public class Factory {
    // ..
    public virtual ICollection<Machine> Machines { get; set; }
}

// ...
IList<Factory> set;
using (MyContext context = new MyContext()) {
    set = context.Factories.ToList();
}

... later on

// Is it possible to check if .Machines is loaded here?
if (set.First().Machines == Loaded)

    // Let's open a new context and load it then
}

The solution I have found when searching for this is to use Include() and just include the machines in the first run, but I would like to avoid loading it until neccessary. I also tried to box it in a new using(...){} but I still get the exception.
I'd also like to avoid Attach since it is extremely slow when building large object graphs.

I guess I could use a bool IsMachinesLoaded or something, but I figured there ought to be some way to check it without that..

Upvotes: 1

Views: 1199

Answers (2)

default
default

Reputation: 11635

I solved it with a method:

protected bool IsLoaded<TEntity>(TEntity entity, Func<TEntity, object> testAction)
{
    try
    {
        testAction(entity);
        return true;
    }
    catch (ObjectDisposedException)
    {
        return false;
    }
}

which is called via:

if (IsLoaded(myEntity, entity => entity.MyList)){
    // the navigational property exists and can be accesses
}

Upvotes: 4

Andreas
Andreas

Reputation: 1081

You will have to read .Machines inside your original DataContext scope, or specify Machines in .Include.

The reason for this is that you are disposing your DbContext before the Machines have been fetched. And when you are trying to fetch, it has no context to do so with. Therefore the ObjectDisposedException.

You cannot just wrap it in another using, as the original DbContext is still disposed, and that is what the entity is bound to.

Upvotes: 0

Related Questions