4

I'm using EF5 database-first with test and prod database servers (identical schemas) on an ASP.NET Web Forms app (4.5). Is there a way to dynamically set the target connection string in Application_Start of global.asax? So when I'm on the test server use the "test" connection string and when I'm on the prod server use the "prod" connection string.

3
  • Why don't why use different config files for each environment? Commented Dec 18, 2012 at 16:11
  • That is definitely an option, but in this case we need a way to change the connection on Application_Start. Commented Dec 18, 2012 at 16:17
  • I don't know about changing in Application_Start, but it looks like you can use the partial method OnContextCreated() on your ObjectContext to change the connection string. I say "looks like" because I've done something similar with LINQ to SQL, but not with EF. Commented Dec 18, 2012 at 16:56

3 Answers 3

1

Did you take a look at http://msdn.microsoft.com/en-us/library/gg679467%28v=vs.103%29.aspx DbContext(string connection)?

ObjectContext: http://msdn.microsoft.com/en-us/library/bb739017.aspx

Keep in mind that the connection string of ObjectContext is not a classic connection string but a EF connection string which is more complicated.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="Database1Entities" 
         connectionString="metadata=res://*/Model1.csdl
|res://*/Model1.ssdl
|res://*/Model1.msl;
provider=System.Data.SqlClient;provider connection string="
Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;
Integrated Security=True;
User Instance=True;
MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
  </connectionStrings>
</configuration>

See also http://msdn.microsoft.com/en-us/library/system.data.entityclient.entityconnection.aspx. With entity-connection, you can create a ObjectContext based on a anready existing classical DbConnection.

Sign up to request clarification or add additional context in comments.

Comments

0

Hopefully this helps someone else - but it looks like we'll be able to figure out a way to do this by following this example: https://stackoverflow.com/a/8240733/448704

Comments

0

For these kind of tasks I would suggest using built in to VS tools. Using them Visual Studio will automatically switch configuration (not only connection string) based on server you want to publish. Check out this link for more info: Web Deployment Made Awesome

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.