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

2023-12-04

我正在使用 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.我只能通过重新启动应用程序池来恢复。

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

启动.cs

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

我正在使用如下扩展方法在 owin 管道中加载数据:

启动.cs

app.LoadTenantData();

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();
        });
    }

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

我该如何调试这个?我是否错误地使用了 EF?


我遇到了同样的问题。

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

EF Core - System.InvalidOperationException:ExecuteReader 需要打开且可用的连接。连接的当前状态已关闭 的相关文章

随机推荐