Robert
Robert

Reputation: 11

Where to set MVC 3 Connection Strings in code

I would like to connect to an existing database, and I put the connection string in the ConnectionStrings section of the Web.Config. But where and how do you refer to this connection in the code. For example, I try things like

string connString = System.Configuration.ConfigurationManager.ConnectionStrings["MyDatabase"].ToString();

in my C# code right before I read the database.

The only way I can make it work is to hard-code the connection string in the C# code, because I don't know how to get it from Web.Config.

Upvotes: 1

Views: 1552

Answers (1)

bkaid
bkaid

Reputation: 52063

That code you have is correct (i fixed one small typo with it). Make sure you add a reference to System.Configuration to your project. And obviously make sure that "MyDatabase" exists as a connection string in the project's web.config.

Upvotes: 1

Related Questions