ef core sqlconnection tryopen nullreferenceexception

ef core sqlconnection tryopen nullreferenceexception

当我使用预先构建的(在我们的自定义基础中)数据库上下文时,我收到一个奇怪的错误,我收到以下异常

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)

如果我使用同一数据库上下文的新实例,错误将消失。我注意到,当我们使用预构建的上下文获得 DbConnection 时,连接没有连接字符串,但对于新实例,它设置正确。

我使用 OnConfiguring 配置提供程序如下:

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

我在这里放置了一个断点,每次连接字符串都设置为相同的值。所以我不明白同一上下文的一个实例如何具有空连接字符串。

有人知道问题的根本原因吗?

谢谢,

所以发生这种情况是因为我正在处理从 context.Database.GetDbConnection() 检索到的连接。我为需要连接字符串的 SqlQuery 和 ExecuteCommand 创建了 polyfill。因此,一旦其中一个被调用,我将失去当前上下文的连接。