Although this question seems like have answers already but my case is different, here's how.
It works the first time but fails for subsequent requests.
I'm creating the connection in the main class and passing to the DB class as a dependency in it's constructor and it's meant to be re-used for each call.
public class DB
{
private SqlConnection conn;
public DB(SqlConnection conn)
{
this.conn = conn;
}
public List<Records> GetRecords()
{
using (conn){
conn.Open();
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Records", conn))
using (SqlDataReader reader = cmd.ExecuteReader())
{
List<Records> rows = new List<Records>();
while (reader.Read())
{
rows.Add(new Records(reader.GetString(1)));
}
return rows;
}
}
}
}
Caller class
string connection = $@"
Data Source=;
Initial Catalog=;
Persist Security Info=True;
User ID={env["DATABASE_USER"]};
Password={env["DATABASE_PASSWORD"]};";
Db db = new DB(new SqlConnection(connection));
db.GetRecords();
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1] An unhandled exception has occurred while executing the request. System.InvalidOperationException: The ConnectionString property has not been initialized.