[英]Object Instance has been disposed (EF)
I'm having some problems with retrieving my Project entity in the EntityFramework. 我在EntityFramework中检索我的Project实体时遇到一些问题。 It keeps giving me the Objest instance has been disposed error.
它一直在给我Objest实例已被处置的错误。
I've got 2 instances, as seen in the image below. 我有2个实例,如下图所示。
And the following code gives me the error: 下面的代码给了我错误:
public Project GetProjectyById(int id)
{
using (var context = new CoderaDBEntities())
{
return context.Projects.First(c => c.Id == id);
}
}
Everything from Project is retrieved fine, but the Category object inside the Project object (the association) delivers me the object has been disposed error. 可以从Project中检索所有内容,但是Project对象(关联)中的Category对象为我提供了该对象已被处置的错误。 What's going on?
这是怎么回事?
Thanks! 谢谢!
Edit: Does this association look odd to you? 编辑:这种关联对您来说看起来很奇怪吗?
It looks like you are attempting to access the Category related object using Lazy Loading when the DBContext object has already been disposed (wrapping it in a using statement will dispose it once it goes out of scope). 似乎您已经尝试在已经处置了DBContext对象时使用“延迟加载”来访问与Category相关的对象(将其包装在using语句中,将在其超出范围时对其进行处置)。 Lazy Loading is when EF loads related entities only when they are requested in the code.
延迟加载是指EF仅在代码中请求相关实体时才加载它们。
To avoid this you should explicitly load the related object with a Include statement : 为了避免这种情况,您应该使用Include语句显式加载相关对象:
return context.Projects.Include("Category").First(c => c.Id == id);
alternatively you could load this in a strongly typed fashion as below but be sure to add the 'using System.Data.Entity; 或者,您可以按如下所示以强类型加载此方法,但请确保添加“ using System.Data.Entity; ' reference
参考
return context.Projects.Include(x => x.Category).First(c => c.Id == id);
Another alternative is to allow for Lazy Loading by not wrapping the DbContext object in a using statement as below. 另一种选择是通过不将DbContext对象包装在using语句中来允许延迟加载,如下所示。
public Project GetProjectyById(int id)
{
var context = new CoderaDBEntities()
return context.Projects.First(c => c.Id == id);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.