views:

239

answers:

3

I'm trying to figure out how to create a dynamic context, and what I mean by that is I have two databases: one for testing, and one for production. Depending on where my website is hosted, I want my context to be pointing at one of the two. So, in my web.config I have:

<add name="Testing_ChannelsEntities" connectionString="removed for brevity" providerName="System.Data.EntityClient" />
<add name="Production_ChannelsEntities" connectionString="removed for brevity" providerName="System.Data.EntityClient" />

Please don't get hung-up on the fact that I removed the connectionString for this example. Just note that I have a testing and a production connection in the web.config.

So, here is my codebehind that I would expect to create a context to the testing connectionString:

using (ChannelsEntities chEntity = new ChannelsEntities("Testing_ChannelsEntities")) {
    // removed the business logic because it's not relevant at all
}

Once execution hits the using statement, I get the following error:

Format of the initialization string does not conform to specification starting at index 0.

What am I missing here? This should be easy to do.

A: 

Try:

using (ChannelsEntities chEntity = new ChannelsEntities(WebConfigurationManager.ConnectionStrings["Testing_ChannelsEntities"].ConnectionString)) {
    // removed the business logic because it's not relevant at all
}
geoff
Unfortunately, the WebConfigurationManager library is part of System.Web, and I have this part abstracted into a business library (Class Library), which of course doesn't reference the System.Web libraries. I could set it up to do so, but I don't want to go down that route unless I have to. Also, the ConnectionStrings is a property, not a method, so I'm not sure your exact syntax would do the trick anyway.
Jagd
I did some testing on this, and found that it will work, but I had to tweak it a little. I had to add references to the System.Web.Configurations library in my business layer, and I had to modify the ConnectionStrings to be used as a enumerated property. I see that you edited your code to do so now, so I suppose that point is mote.
Jagd
I program mainly in vb.net hence the parenthesis rather than square brackets. Glad you got it working.
geoff
A: 

I've done similar. Try this -

using (ChannelsEntities chEntity = new ChannelsEntities("name=Testing_ChannelsEntities")) {}
The Beaver
Surprisingly, this works. I didn't expect it to because of the whole "name=", but constructor must be handling it somehow.
Jagd
A: 

We put our connection string in a root web.config. You can reference the connection string by name in your virtual diectory and it will inherit the settings from your root web.config.

Andrew Robinson