ASP.NET MVC 2, SQL-Connection string reuse
so I am very far from being an MVC or ASP.NET expert. I just want to make some simple controllers in C # for now, so I have the following question:
Right now I have a connection string used by a controller - internal - the controller itself. What nonsense when there are multiple controllers using the same string. I would like to be able to change the connection string in only one place and affect all controllers.
Without knowing a lot about asp.net or the "m" and "v" parts of MVC, what would be the best (and easiest) way to do just that?
I would appreciate any input on this, examples would be great.
a source to share
You can add a connection string to your web.config file like this:
<configuration>
<appSettings>
<add key="ConnectionString"
value="server=localhost;database=Northwind;uid=sa;password=secret;"/>
</appSettings>
<system.web>
<customErrors mode="Off"/>
</system.web>
</configuration>
and use it in your code like this:
strConnection = ConfigurationSettings.AppSettings("ConnectionString") // <-----
sqlConn = New SqlConnection(strConnection)
sqlCmd = New SqlCommand("SELECT * FROM Customers WHERE " & "(CompanyName LIKE 'A%') OR (CompanyName LIKE 'B%')", sqlConn)
Pay attention to the first line. This example is for VB, but you should be able to do the same in C #.
The example is taken from this link http://www.dotnetjohn.com/articles.aspx?articleid=3 , but there are many.
Hope it helps.
a source to share
Place it in your web.config file like this:
<connectionStrings>
<add name="ConnectionName" connectionString="TheConnectionString" providerName="System.Data.SqlClient" />
</connectionStrings>
<connectionStrings>
is just a child of the root <configuration>
.
Then you can read it like:
string myConnStr = ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString;
HTHS, Charles
a source to share