How do you get the connection string from the startup.cs
public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } // code ----------------------------- // Add our db services.AddDbContext<NextGenerationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); // Add application services here services.AddTransient<IServiceAuth, ServiceAuthc>(); }
In my appsettings.json ... "DefaultConnection: "Server=my string";
Here is my static connection class:
public static class Connection { public static string ConnectionString { get; set; } public static SqlConnection ConnectionFactory() { return new SqlConnection(ConnectionString); } }
Here is the method I'm trying to pass the string too. This a service.
public int InsertPersonActivityLog(int logId, string edi, string personFormalName, DateTime activityDateTime, string activityTypeDescriptor, string additionalDetails, string reasonMessage, string notes)
{
SqlConnection conn = new SqlConnection();
// Get the connection string from the appsettings.Development.json
conn.ConnectionString = // here is where I'm trying to pass my connectionstring.
// Open the connection
conn.Open();
// Set connection property of command object.
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
// Set the command type of the command object.
cmd.CommandType = System.Data.CommandType.StoredProcedure;
// Assign values as "parameters to avoid 'SQL Injections.'"
cmd.Parameters.AddWithValue("@edi", edi);
cmd.Parameters.AddWithValue("@formalName", personFormalName);
cmd.Parameters.AddWithValue("@date", activityDateTime);
cmd.Parameters.AddWithValue("@descriptor", activityTypeDescriptor);
cmd.Parameters.AddWithValue("@details", additionalDetails);
cmd.Parameters.AddWithValue("@reason", reasonMessage);
cmd.Parameters.AddWithValue("@notes", notes);
return cmd.ExecuteNonQuery();
}