DB Connection Setup with Factory Pattern not returning ConnectionString

546 views Asked by At

I am looking to setup a Factory to get my connection to my database. I thought I had set everything up correctly, but I must be missing something because my ConnectionString is not returning when I use .CreateConnection().

My thoughts are that I missed something in my App.config connection string for this to not be working.

This is my first time trying to do this and I was hoping someone could explain to me what I am missing. Thanks!

Here is my code:

const string SQL_CONNECTION_KEY = "MSDBConnection";
var connString = ConfigurationManager.ConnectionStrings[SQL_CONNECTION_KEY];
var providerName = connString.ProviderName;
var factory = DbProviderFactories.GetFactory(providerName);
var conn = factory.CreateConnection();

var conn does not seem to populate with my App.config connection... Here is my ConnectionString:

<connectionStrings>
  <add name="MSDBConnection" connectionString="server=.;database=msdb;user id=UserName;password=Password;" providerName="System.Data.SqlClient"/>
</connectionStrings>

Again, any help would be much appreciated. Thanks!

1

There are 1 answers

2
juharr On BEST ANSWER

You're not setting the connection string on your connection. Try this.

conn.ConnectionString = connString.ConnectionString;