【发布时间】:2016-10-20 15:18:35
【问题描述】:
我看到 无法完成操作,因为 DbContext 已被释放。 异常消息,即使代码通过返回 List
public List<Entity> GetEntityByProperty(string property)
{
using (AppDbContext appDbContext = GetContext())
{
List<Entity> entities = appDbContext.Entities
.Where(e => e.Property == property)
.ToList();
return entities;
}
}
这又是从 Web 服务类调用的:
private static EntityRepository EntityRepositoryStatic = new EntityRepository();
[WebMethod]
public List<Entity> GetEntityByProperty(string property)
{
return EntityRepositoryStatic.GetEntityByProperty(property);
}
EntityRepository 继承自一个 Repository 基类,该基类实现了 IDisposable(用于处理上下文),并通过此代码返回一个上下文:
private AppDbContext appDbContext;
public AppDbContext GetContext()
{
if (appDbContext == null)
{
appDbContext = new AppDbContext();
}
return appDbContext;
}
在调用存储库中的 appDbContext 的行上会引发异常。我错过了什么明显的东西吗?
这是一个大型遗留代码库,因此我们只是尝试用对存储库类的调用替换对 Web 服务中上下文的内联调用。
【问题讨论】:
-
你没有在这里使用eager loading。调用此方法后,您无法延迟加载相关实体,因为 db 已被释放,因此此处的 Eager Loading 将是更好的选择。在这里查看stackoverflow.com/a/34628138/2946329
-
抱歉 -
GetContext()打印错误 - 应该是appDbContext- 我现在会更新它。 -
@BWHazel 好吧,您需要使用
Include来使用 eager loading 并摆脱此错误。查看我链接的示例以了解方法和解释。
标签: c# entity-framework linq