Check if navigational property is loaded

谁都会走 提交于 2020-01-05 08:42:10

问题


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..


回答1:


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
}



回答2:


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.



来源:https://stackoverflow.com/questions/22545823/check-if-navigational-property-is-loaded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!