问题描述
假设:
public ActionResult List()
{
using (var unitOfWork = new UnitOfWork())
{
var result = unitOfWork.Repository.Find<EntityAddress>(a => a.PostalCode == "80001");
//return View(result.ToList());//NO Exception raised with ToList()
return View(result);//EXCEPTION RAISED IN VIEW DURING ITERATION
}
}
的UnitOfWork
是一次性的,处理处置我的DbContext的。它还禁止在构造函数中延迟加载:
UnitOfWork
is disposable and handles disposal of my DbContext. It also disables lazy loading in the constructor:
public UnitOfWork()
{
_dbContext.Configuration.LazyLoadingEnabled = false;
Repository = new GenericRepository<MyEntities>(_dbContext);
}
public void Dispose()
{
Repository.Dispose();
}
以及查找&LT; EntityAddress&GT;()
实施工程以:
_dbContext.Set&LT; EntityAddress方式&gt;()式(predicate)
其中predicate是类型的参数防爆pression&LT;&Func键LT; EntityAddress,布尔&GT;&GT;
_dbContext.Set<EntityAddress>().Where(predicate)
where predicate is a parameter of type Expression<Func<EntityAddress, bool>>
为什么会处置例外,甚至在我禁用延迟加载?
Why do I get a disposal exception even after I disabled lazy loading?
推荐答案
懒惰和渴望装载有难同当实体的做相关的到您的查询(如导航属性和集合)被加载,而不是当查询的内容本身被加载
Lazy and eager loading have to do with when entities related to your query (e.g. navigation properties and collections) are loaded, not when the contents of the query itself are loaded.
的 IQuerable&LT; EntityAddress&GT;
从你的资料库&MDASH退换;无论您是否已经启用了延迟加载&MDASH;不会在服务器上运行查询,直到它列举(不管是由获得在的foreach
循环枚举器,调用<$c$c>Enumerable.ToList<TSource>$c$c>其上,或把它变成一个调用<$c$c>Controller.View$c$c>下游渲染)。
The IQuerable<EntityAddress>
returned from your repository—whether or not you have lazy loading enabled—will not run the query on the server until it's enumerated (whether that's by getting an enumerator in a foreach
loop, calling Enumerable.ToList<TSource>
on it, or passing it into a call to Controller.View
for downstream rendering).
在这种情况下得到异常的原因是因为<$c$c>Controller.View$c$c>不会立即呈现视图(并且因此不会立即枚举查询)。它所做的就是构造的一个实例<$c$c>ViewResult$c$c>保存到模型参数(查询对象),直到MVC确实使后来的看法,你处理你的背景之后。
The reason you get an exception in this case is because Controller.View
does not immediately render the view (and therefore does not immediately enumerate the query). All it does is construct an instance of ViewResult
that holds onto the model parameter (your query object) until MVC does render the view later on, after you've disposed your context.
如果您想查询结果传递给视图,你有两个选择:
If you want to pass query results to a view, you have two options:
- 扩展数据库上下文的寿命到控制器的寿命
- 呼叫<$c$c>Enumerable.ToList<EntityAddress>$c$c>在
IQuerable&LT;相反
的; EntityAddress&GT; 数据库上下文配置之前,并使用所产生的列表&LT; EntityAddress&GT
IQuerable&LT; EntityAddress方式&gt;
- Extend the life of the database context to the lifetime of the controller
- Call
Enumerable.ToList<EntityAddress>
on theIQuerable<EntityAddress>
before the database context is disposed, and use the resultingList<EntityAddress>
instead of theIQuerable<EntityAddress>
.
这篇关于&QUOT;不能完成该操作,因为的DbContext已被释放&QUOT;懒负载例外禁用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!