Why do I get a "ConnectionString property has not been initialized" error on the first call to a stored procedure with Entity Framework Core?

Viewed 3950

I have a service in ASP.NET Core to which I inject my Entity Framework Core context that is used to define a private func that my service will need. That func is about calling a stored procedure.

The first call to that func systematically leads to an error

The ConnectionString property has not been initialized.

However, subsequent calls are fine.

Here is the service class constructor:

private readonly Func<Task<long>> _myFunc;

public MyService(MyContext context) => _myFunc= async () =>
    {
        using (var connection = context.Database.GetDbConnection())
        {
            await connection.OpenAsync();

            using (var command = connection.CreateCommand())
            {
                command.CommandType = CommandType.StoredProcedure;
                command.CommandText = "sp_MyStoredProcedure";
                command.Parameters.Add(new SqlParameter("@AParameter", SqlDbType.Int) { Value = 1 });
                return (long)await command.ExecuteScalarAsync();
            }
        }
    };

Here is the stacktrace:

System.InvalidOperationException: The ConnectionString property has not been initialized.

at System.Data.SqlClient.SqlConnection.PermissionDemand()
at System.Data.SqlClient.SqlConnectionFactory.PermissionDemand(DbConnection outerConnection)
at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource
1 retry, DbConnectionOptions userOptions)
at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) at System.Data.SqlClient.SqlConnection.OpenAsync(CancellationToken cancellationToken) --- End of stack trace from previous location where exception was thrown --- at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenDbConnectionAsync(Boolean errorsExpected, CancellationToken cancellationToken)

UPDATE:

When I set a breakpoint on line await connection.OpenAsync() and look at the variable connection the connection string is there and correct.

Note that MyServices is injected into a controller constructor. The service registration is done this way in startup.cs:

services.AddTransient<IMyService, MyService>();
1 Answers

Try not to disposing of the connection as suggested in https://stackoverflow.com/a/10911844/532575.

So, basically, replace using (var connection = context.Database.GetDbConnection()) with var connection = context.Database.GetDbConnection() and see whether it helps.

Related