Dara Oladapo
Dara Oladapo

Reputation: 596

[ASP.NET]-Connection String Manipulation in ApplicationDbContext

I had a challenge today at work (Solved already but I'll like to put it out here maybe there is a better and smarter way of doing it) I am working on VSTS with git on a project with another developer. We use different connection strings so what we do is when I pull, I comment his connection string and activate mine. When he pulls, he comments mine and activates his.

We don't want to create another git-branch.

What is the best way to achieve this?

Upvotes: 0

Views: 53

Answers (1)

Dara Oladapo
Dara Oladapo

Reputation: 596

Here is an instance of how I did it.

Editing my Web.Config file
Note: the names: DefaultConnection, LocalConnection, livedbsource, localdbsource, localMachineName

 <connectionStrings>
 <!--Live-->
 <add name="DefaultConnection" connectionString="Data Source=livedbsource;Initial Catalog=livedbname;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False;MultipleActiveResultSets=true;" providerName="System.Data.SqlClient" />
<!--Dev-->
<add name="LocalConnection" connectionString="Data Source=localdbsource;Initial Catalog=localdbname;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False;MultipleActiveResultSets=true;" providerName="System.Data.SqlClient" />
</connectionStrings>

And for the ApplicationDbContext

 static string ServerName = System.Net.Dns.GetHostName();
    //setting what connection string to use - tenary operator
    static string ConnectionStringID = (ServerName == "localMachineName") ? "LocalConnection" : "DefaultConnection";
    public ApplicationDbContext()
        : base(ConnectionStringID, throwIfV1Schema: false)
    {
    }

On Windows 7 and higher, You can get the localMachineName pressing the Windows Logo and searching for System Information, then look for 'System Name'

Here is the YouTube video I did it in Visual Studio 2017 on a live project and it worked.

https://youtu.be/oKg6ewKhkYs

Upvotes: 2

Related Questions