Skip to main content
 首页 » 编程设计

c#之检查是否加载了导航属性

2024年02月13日11虾米哥

是否可以检查是否已加载导航属性?当我尝试访问它时,我只得到一个 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 
} 

我在搜索时找到的解决方案是使用 Include() 并且只在第一次运行时包含机器,但我想避免在必要时加载它。我也尝试将其装入新的 using(...){} 但我仍然遇到异常。
我还想避免使用 Attach,因为它在构建大型对象图时非常慢。

我想我可以使用 bool IsMachinesLoaded 或其他东西,但我想应该有一些方法可以在没有它的情况下检查它..

请您参考如下方法:

我用一个方法解决了:

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 
}