我希望最终能查清 Entity Framework DbContexts 持续存在的问题。我的问题的历史是偶尔 - 特别是当请求快速连续进入时 - 我的 DbContext 抛出各种奇怪的错误,包括以下内容:
System.InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first.
System.InvalidOperationException: Internal connection fatal error.
我的 MVC 代码基于一个基本模式,其中我有一个基本 Controller ,如下所示:
public class BaseController : Controller
{
protected readonly DbContext db = new DbContext();
protected override void Dispose(bool Disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
所有其他 Controller 都派生自该基本 Controller ,从而使 DbContext 在必要时可用于 Controller 操作,这些操作都不是异步的。唯一的异常(exception)是我的自定义授权,它还在访问时创建一个 DbContext 并在几乎每个 Controller 操作中调用(通过属性):
public class MyAuthorizeAttribute : AuthorizeAttribute
{
private DbContext db;
protected override bool IsAuthorized(HttpActionContext actionContext)
{
db = new DbContext();
var user =
db.Security.FirstOrDefault(u =>
u.Id == actionContext.ControllerContext.Request.Headers.First(h =>
h.Key == "Id").Value);
return (user != null);
}
}
我还尝试了以下方法但无济于事:
- 从我的 Controller 操作中删除所有异步
- 从 DbContext 中删除延迟加载并在每次调用时插入显式 Include 语句
查看 StackOverflow,其他人似乎也有类似的问题:
- Weird race conditions when I send high frequency requests to my datacontext
- Random errors occur with per-request DbContext
这两个答案都没有真正帮助我找到问题的根源,但是第二个 SO 帖子的 OP-answer 说 (“经过进一步调查,我发现请求处理线程有时会从其他线程窃取 DbContext”) ,但我不确定这是否真的适用。
我的设计是否存在根本性错误?将每个 Controller 操作的 DbContext 包装到 using block 中是不正确的,即使 this blog说是 - 但这不会导致其他问题,例如返回不再附加到 DbContext 的对象(因此失去更改跟踪)...?
最佳答案
when requests come in in fast succession
大约一年前让我想到了一个问题,所以我认为它与 EF6 无关。但是,我花了很长时间才弄明白。
允许您的数据库对每个应用程序有多个未决请求。将您的连接字符串更改为 MultipleActiveResultSets=True
关于c# - MVC/EF6/WebApi2 应用程序中 DbContext 使用的正确模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21228927/