【问题标题】:Using one connection for Context object in EF在 EF 中为 Context 对象使用一个连接
【发布时间】:2013-07-08 07:47:30
【问题描述】:

如何在 EF 中为两个查询使用相同的连接,例如我在 MVC 控制器中编写了这段代码:

    DataLayer.Context context = new DataLayer.Context();

    [ChildActionOnly]
    public int TodayVisits()
    {
        return Repository.VisitsRepository.TodayVisits(context);
    }

    [ChildActionOnly]
    public int LastMonthVisits()
    {
        return Repository.VisitsRepository.LastMonthVisits(context);
    }

我正在使用应用程序检查输出 T-SQL,它显示连接 2 时间已打开。

【问题讨论】:

  • 这两个函数是否在同一个 MVC 动作中执行?你怎么称呼他们?
  • TodayVisits 和 LastMonthVisits 是同一个控制器中的操作,我在这个控制器中有一个上下文对象,我将其命名为上下文

标签: entity-framework model-view-controller connection sql-server-profiler


【解决方案1】:

对于来自浏览器的每个请求,controller instance will be created.. 因此它也会为每个请求创建新的上下文。 并阅读此内容,What is the 'page lifecycle' of an ASP.NET MVC page

为每个请求创建 DbContext 实例的更多内容是common practice for entity framework

编辑..
如果需要处理连接,则需要将连接传递给 DbContext 构造函数并设置contextOwnsConnection=false。请参阅documentation 并尝试一下。 在这里阅读更多..DbContext won't keep connection open for re-use

【讨论】:

  • 如您所见,我有 2 个 ChildActionOnly 方法。我想在每个请求中使用一次打开的连接,我在同一个请求中调用这些操作,但我监视了两个打开的连接。
猜你喜欢
  • 2020-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-05
  • 1970-01-01
  • 2020-10-07
相关资源
最近更新 更多