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)
1 retry, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource
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>();
command.Connection = connection;
before opening theawait connection.OpenAsync()
GetDbConnection
returns the connection of the database of the context which is injected and properly setup.connection.CreateCommand
surely links thecommand
and theconnection
already.sp_
prefix for your stored procedures. Microsoft has reserved that prefix for its own use (see Naming Stored Procedures), and you do run the risk of a name clash sometime in the future. It's also bad for your stored procedure performance. It's best to just simply avoidsp_
and use something else as a prefix - or no prefix at all!