c# - MVC/EF6/WebApi2 应用程序中 DbContext 使用的正确模式

标签 c# design-patterns asp.net-web-api asp.net-mvc-5 dbcontext

我希望最终能查清 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,其他人似乎也有类似的问题:

这两个答案都没有真正帮助我找到问题的根源,但是第二个 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/

相关文章:

c# - 如何格式化数字以具有相同的位数?

c# - 按对象类型解析服务的设计模式?

c# - 如何在客户端不发送任何请求的情况下从 Windows Azure 服务器向客户端移动应用程序(iOS)发送消息?

c# - 获取 OU 的完全限定名称

c# - 当光标悬停在 asp.net 网站中的图像上时如何更改图像

node.js - React Flux 调度程序与 Node.js EventEmitter - 可扩展吗?

c# - 从 web api 调用 aspx 页面时出现“无效的 URI : The format of the URI could not be determined.”

asp.net-web-api - Asp.net 身份,生成 WebApi token OAuthGrantResourceOwnerCredentialsContext - 无法使用 Unity 访问 UserManager

c# - 根据其他列中的值在 gridview 列中显示图像

sql - 布线数据库的数据库方案