EF Core - System.InvalidOperationException: ExecuteReader requires an open and available Connection. The connection's current state is closed

asp.net-core c# entity-framework entity-framework-core

Question

I'm running an ASP.NET Core 1.0 web app with Entity Framework Core. When the app has been running for a while (24 - 48 hours), the app starts crashing on every request to any endpoint or static resource throwing the error System.InvalidOperationException: ExecuteReader requires an open and available Connection. The connection's current state is closed. I can only recover from this by restarting the App Pool.

I am configuring Entity Framework like this:

Startup.cs

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

I am loading data in the owin pipeline with an extension method like this like this:

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

Since the error only occurs when the app has been running for a long time, it is hard to reproduce, but I'm assuming it has something to do with EF opening and closing connections incorrectly.

How can I go about to debug this? Am I using EF incorrectly?

1
5
8/1/2016 11:47:26 AM

Popular Answer

I got same issue.

I think it is likely that the same dbcontext instance is being used concurrently by multiple threads.

You may need this: services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")),ServiceLifetime.Transient); There is a issue about that. https://github.com/aspnet/EntityFramework/issues/6491

4
9/20/2016 3:53:46 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow