Change connection string in Entity Framework 4.1 POCO

I use EF4.1, updated my project, generated POCO classes to use DbContext now and had fun - except for changing connection strings on the fly. These projects import CSV files and then combine the data into two (identical) databases. One database is our PROD server, the other is our DEV server. I understand how I made the changes (below) no longer works when I switched to POCO.

What did I do:

internal static Model.RIVFeedsEntities GetFeedsDB() { _serverName = "RivDB1"; // Create the dbZach database entity... EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder(); string connString = String.Format(@"metadata=res://*/Model.Feeds.csdl|res://*/Model.Feeds.ssdl|res://*/Model.Feeds.msl;provider=System.Data.SqlClient;provider connection string='Data Source={0};Initial Catalog={1};Integrated Security=True;MultipleActiveResultSets=True'" , _serverName , _databaseName); entityBuilder.ConnectionString = connString; entityBuilder.Metadata = "res://*/"; _sourceEntities = new Model.RIVFeedsEntities(entityBuilder.ConnectionString); _sourceEntities.CommandTimeout = 60; return _sourceEntities; } internal static Model.RIVFeedsEntities GetFeedsDBDev() { _serverName = "DB1"; // Create the dbZach database entity... EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder(); string connString = String.Format(@"metadata=res://*/Model.Feeds.csdl|res://*/Model.Feeds.ssdl|res://*/Model.Feeds.msl;provider=System.Data.SqlClient;provider connection string='Data Source={0};Initial Catalog={1};Integrated Security=True;MultipleActiveResultSets=True'" , _serverName , _databaseName); entityBuilder.ConnectionString = connString; entityBuilder.Metadata = "res://*/"; _sourceEntities = new Model.RIVFeedsEntities(entityBuilder.ConnectionString); _sourceEntities.CommandTimeout = 60; return _sourceEntities; } 

As you can see, all I really need to do is change the SERVER part of the connection string.

How do you do this using a DbContext object? I see that the database allows you to send the name or string conn in the constructor, but DbContext itself does not, and I can’t see anything.

TIA

+4
source share
1 answer

When you inherit from DbContext, there are several DbContext constructors from which you can override.

You can choose from a different signature to find the one that suits you.

in this forum http://social.msdn.microsoft.com/Forums/en/adodotnetentityframework/thread/2efc32f7-23ad-4fad-84cf-279badb394a5

they use either an SqlConnection object or ConnectionString.

I think this still applies to the RTW version of EF 4.1

+1
source

All Articles