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.
-
Why don't why use different config files for each environment?Rui Jarimba– Rui Jarimba2012-12-18 16:11:34 +00:00Commented 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.Rob Lauer– Rob Lauer2012-12-18 16:17:33 +00:00Commented 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.Mike Hildner– Mike Hildner2012-12-18 16:56:09 +00:00Commented Dec 18, 2012 at 16:56
3 Answers
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.
Comments
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
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