user2471435
user2471435

Reputation: 1674

How to use 2 different connection strings in a single project?

We have a scenario where we have two SQL Server databases, one for testing and one for deployment. When I came onto the project, they had been using typed datasets and passing the connection string to determine which database. There was only one typed dataset for both.

Now, I am trying to do this with Entity Framework. While I could have two EDMX models in the same Class Library, the catch is both databases have the same tables, therefore generate the same C# classes with the same names and there is collisions.

Is there anyway to deal with this scenario?

Upvotes: 1

Views: 939

Answers (3)

OuttaSpaceTime
OuttaSpaceTime

Reputation: 966

for me the following was sufficient regarding using a gitlab ci which holds the name runner within it.

public static string GetConnectionString(IConfiguration configuration)
        {
            if (Environment.MachineName.Contains("runner"))
            {
                return configuration.GetConnectionString("DatabasePipeline");
            }
            return configuration.GetConnectionString("DatabaseLocal");
        }

Upvotes: 0

meda
meda

Reputation: 45490

One thing you do is setup your webconfig file to point to your production DB server when you set it to release or publish it.

If you are debugging it then it will point to your development SQL server.

It is very easy to set up, the webconfig file contains web.Release.config and web.Debug.config, this is where you set it to replace the connection string.


  <!--
    In the example below, the "SetAttributes" transform will change the value of 
    "connectionString" to use "ReleaseSQLServer" only when the "Match" locator 
    finds an atrribute "name" that has a value of "MyDB".

    <connectionStrings>
      <add name="MyDB" 
        connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True" 
        xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
    </connectionStrings>
  -->

In your case you will put the replace attribute.

Upvotes: 5

Sameer
Sameer

Reputation: 3183

You can take the overloaded version of Objectcontext from which your model is derived that takes connection string as parameter

Upvotes: 0

Related Questions