ObjectDisposedException 尽管使用了 *Include*
ObjectDisposedException despite *Include* being used
在我的视图模型中,我正在执行以下操作。
public List<Order> Orders { get; set; }
public ViewModel()
{
using (Context context = new Context())
Orders = context.Orders
.Include(order => order.Status).ToList();
}
Order test1 = Orders.First(item => item.Status != null);
Order test2 = Orders.First(item => item.Status != null && item.Status.Id == 1);
所以我已经包含了导航属性并将它们放在那里以备将来使用。但是,如果我四处查看并展开正在观看的对象,我会发现状态实际上没有任何价值。它会产生以下错误。
'(test1.Status).Orders' threw an exception of type 'System.ObjectDisposedException'
现在,我的理解是,如果我忘记使用 Include(),这就是结果,因为实体超出了上下文的范围并被处置。但在这种情况下,他们不是,我很清楚为什么。
建议?我错过了什么?
在我四处寻找之后,我无法停止,但有这样一种印象,即包含 Status 是正确的,但它反过来不包含参考回到原来的 Order。我对如何处理它有点困惑...
此处的问题是您的 context
默认具有 LazyLoadingEnabled=true
,因此 Include
不会为每个急切加载的 Status
设置后向引用。您可以尝试关闭该上下文的延迟加载,您会看到反向引用也将被正确地预先加载:
using (Context context = new Context()){
context.Configuration.LazyLoadingEnabled = false;
Orders = context.Orders
.Include(order => order.Status).ToList();
}
我刚刚做了一个简单的演示并确认它有效。
在我的视图模型中,我正在执行以下操作。
public List<Order> Orders { get; set; }
public ViewModel()
{
using (Context context = new Context())
Orders = context.Orders
.Include(order => order.Status).ToList();
}
Order test1 = Orders.First(item => item.Status != null);
Order test2 = Orders.First(item => item.Status != null && item.Status.Id == 1);
所以我已经包含了导航属性并将它们放在那里以备将来使用。但是,如果我四处查看并展开正在观看的对象,我会发现状态实际上没有任何价值。它会产生以下错误。
'(test1.Status).Orders' threw an exception of type 'System.ObjectDisposedException'
现在,我的理解是,如果我忘记使用 Include(),这就是结果,因为实体超出了上下文的范围并被处置。但在这种情况下,他们不是,我很清楚为什么。
建议?我错过了什么?
在我四处寻找之后,我无法停止,但有这样一种印象,即包含 Status 是正确的,但它反过来不包含参考回到原来的 Order。我对如何处理它有点困惑...
此处的问题是您的 context
默认具有 LazyLoadingEnabled=true
,因此 Include
不会为每个急切加载的 Status
设置后向引用。您可以尝试关闭该上下文的延迟加载,您会看到反向引用也将被正确地预先加载:
using (Context context = new Context()){
context.Configuration.LazyLoadingEnabled = false;
Orders = context.Orders
.Include(order => order.Status).ToList();
}
我刚刚做了一个简单的演示并确认它有效。