EF核心-System.InvalidOperationException:ExecuteReader需要打开且可用的连接。连接的当前状态为关闭

sev*_*rin 5 c# entity-framework entity-framework-core asp.net-core

我正在使用Entity Framework Core运行ASP.NET Core 1.0 Web应用程序。当应用程序运行了一段时间(24-48小时)后,该应用程序在对任何端点或静态资源的每个请求上开始崩溃,并抛出错误,System.InvalidOperationException: ExecuteReader requires an open and available Connection. The connection's current state is closed.我只能通过重新启动应用程序池来从中恢复。

我正在像这样配置实体框架:

启动文件

public void ConfigureServices(IServiceCollection services)
{
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));   
}
Run Code Online (Sandbox Code Playgroud)

我正在使用这样的扩展方法在owin管道中加载数据:

启动文件

app.LoadTenantData();
Run Code Online (Sandbox Code Playgroud)

AppBuilderExtensions.cs:

public static void LoadTenantData(this IApplicationBuilder app)
    {
        app.Use(async (context, next) =>
        {
            var dbContext = app.ApplicationServices.GetService<ApplicationDbContext>();        
            var club = dbContext.Clubs.Single(c => c.Id == GetClubIdFromUrl(context));
            context.Items[PipelineConstants.ClubKey] = club;
            await next();
        });
    }
Run Code Online (Sandbox Code Playgroud)

由于该错误仅在应用程序已长时间运行时发生,因此很难重现,但我认为它与EF错误地打开和关闭连接有关。

我该如何调试呢?我使用EF是否不正确?

qin*_*qin 6

我遇到了同样的问题。

我认为多个线程可能同时使用同一个 dbcontext 实例。

您可能需要这个: services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")),ServiceLifetime.Transient); 有一个关于此的问题。 https://github.com/aspnet/EntityFramework/issues/6491