检查导航属性是否加载 [英] Check if navigational property is loaded
问题描述
是否可以检查是否已加载导航属性?当我尝试访问它时,我只得到一个 ObjectDisposedException
Is it possible to check if a navigational property has been loaded? When I try to access it I only get an ObjectDisposedException
ObjectContext实例被处理,不能再用于需要连接的操作。
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
}
搜索这个问题的解决方案是使用 Include()
包括机器在第一次运行,但我想避免加载它,直到必要的。我也尝试使用(...){} 新的框,但我仍然得到例外。
我也想避免附加
,因为构建大型对象图时速度非常慢。
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.
我想我可以使用 bool IsMachinesLoaded
或某事,但我认为应该有一些方法来检查它没有..
I guess I could use a bool IsMachinesLoaded
or something, but I figured there ought to be some way to check it without that..
推荐答案
我用一个方法解决了:
protected bool IsLoaded<TEntity>(TEntity entity, Func<TEntity, object> testAction)
{
try
{
testAction(entity);
return true;
}
catch (ObjectDisposedException)
{
return false;
}
}
通过以下方式调用:
if (IsLoaded(myEntity, entity => entity.MyList)){
// the navigational property exists and can be accesses
}
这篇关于检查导航属性是否加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!