herme 0
herme 0

Reputation: 972

ef core sqlconnection tryopen nullreferenceexception

I am getting a strange error when I used a pre-built (in our custom base) db context I get the following exception

System.NullReferenceException: Object reference not set to an instance of an object.
   at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.Open()
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.BufferlessMoveNext(Boolean buffer)
   at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
   at System.Linq.Enumerable.SelectEnumerableIterator`2.MoveNext()
   at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
   at lambda_method(Closure , QueryContext )
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass17_1`1.<CompileQueryCore>b__0(QueryContext qc)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
   at System.Linq.Queryable.SingleOrDefault[TSource](IQueryable`1 source)
   ...(ommitted on purpose)

The error will go away if I use a new instance of the same db context. I noticed that when we get a DbConnection with the pre-built context the connection has no connection string but with the new instance it is set correctly.

I use the OnConfiguring to configure the provider as follow:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    if (!optionsBuilder.IsConfigured)
    {
        if (_provider == Providers.SqlServer)
        {
            optionsBuilder.UseSqlServer(_connectionString);
        }
        else
        {
            throw new NotImplementedException("Provider not supported");
        }
    }
}

I put a breakpoint here and everytime the connection string is set to the same values. So I do not understand how one instance of the same context has an empty connection string.

Does anyone know the root cause of the issue?

Thank you,

Upvotes: 1

Views: 616

Answers (1)

herme 0
herme 0

Reputation: 972

So this happens because I was disposing a connection retrieved from context.Database.GetDbConnection(). I created polyfills for SqlQuery and ExecuteCommand which needed a connection string. So once one of them was called I will lose the current context's connection.

Upvotes: 2

Related Questions