Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to cast object of type 'System.Data.ProviderBase.DbConnectionClosedConnecting' to type 'System.Data.SqlClient.SqlInternalConnectionTds

I am getting the following error on the first db access after the application starts - "Unable to cast object of type 'System.Data.ProviderBase.DbConnectionClosedConnecting' to type 'System.Data.SqlClient.SqlInternalConnectionTds"

The error only thrown once, at the first method tries to read data from the database, after the application starts. Re-calling the same method for the 2nd time and further, everything works fine.

Using .net core 1.1 with Entity Framework

like image 232
Egor Avatar asked Sep 10 '17 07:09

Egor


1 Answers

I recently had this same exception in an ASP.NET Core 2 app with EF Core. In my case, the root cause was a problem with the scopes my dependency-injected DbContext. I had a controller and a service both using an injected DbContext. The service was a singleton, like this:

public class TestService{
  public TestService(FooDbContext db)
    {
        this.db = db;
    }
}

public class FooController{
 public FooController(FooDbContext db, TestService testService) 
 {
        this.testService = testService;
        this.db = db;
 }
}
public class Startup{
  public void ConfigureServices(IServiceCollection services){
      //...
      services.AddDbContext<FooDbContext>(options =>
            options
            .UseSqlServer(Configuration.GetConnectionString("FooDbContext"))
      );
      services.AddSingleton<TestService>();
  }
}

So the controller would use it's instance, and then if the singleton service also tried to use it's own instance, then it would give the error above about 90% of the time. I'm a little fuzzy on why this would be an issue, or be intermittent, but it became pretty clear in debugging that EF was reusing some underlying resources. I didn't dig into EF code debugging, but I suspect the controller instance was closed, and the service instance reused the connection, expecting it to be open. In reading, others suggested MultipleActiveResultSet=true in the connection string would fix, but this did not resolve the issue in my case. In my case, the fix was to change the service to Transient in Startup.cs, which was acceptable in this case, and possibly better:

services.AddTransient<TestService>(); 
like image 198
Daniel Avatar answered Oct 26 '22 11:10

Daniel