Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change connString dynamically

Tags:

c#

sql

I am currently working on an ASP.NET MVC project with Entity Framework. The solution includes the ASP.NET MVC application and a DataProvider project. The project only includes an EF model, as I have a partner who shares a database with me.

The problem is in that, that we don't actually share the same database. What I mean is that the actual server of the database is not the same. We have the same tables. But the connection string has to be changed every single time we pull from our git repository. The string changes in the web.config file of the ASP.NET MVC project and in the app.config file of the EF library.

My question is - if there is a way for our system to detect which PC it is running on and modify the connection string dynamically? Now I do it manually.

<!--PC NICO CEI-->

<!--
<connectionStrings>
    <add name="dbShubertEntities" 
         connectionString="metadata=res://*/ModelDbShubert.csdl|res://*/ModelDbShubert.ssdl|res://*/ModelDbShubert.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=E04\SQLEXPRESS;initial catalog=dbShubert;user id=gereisma17;password=12321;MultipleActiveResultSets=True;App=EntityFramework&quot;" 
         providerName="System.Data.EntityClient" />
</connectionStrings>
-->

<!--PC NICO Laptop-->

<!--
<connectionStrings>
    <add name="dbShubertEntities" 
         connectionString="metadata=res://*/ModelDbShubert.csdl|res://*/ModelDbShubert.ssdl|res://*/ModelDbShubert.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=DESKTOP-I62BLOC;initial catalog=dbShubert;user id=user;password=1234;MultipleActiveResultSets=True;App=EntityFramework&quot;" 
         providerName="System.Data.EntityClient" />
</connectionStrings>
-->

This is what I do now. I am commenting the connection string. I want to automate the whole thing.

like image 951
Nicolás López Avatar asked Jul 31 '26 10:07

Nicolás López


1 Answers

You could overload the DbContext's constructor with the dynamic connection string

public class MasterDal : DbContext
    {
        public MasterDal(string nameOrConnectionString) : base(nameOrConnectionString)
        {

        }
       // DbSet &  OnModelCreating etc 
    }

& then invoke dal in Controller as required

if (logicToGetPc.equal("CEI"))
 { 
    MasterDal dal = new MasterDal("dbShubertEntitiesCEI");
   // do  mumbai related whatever 
 }
 else if (logicToGetPc.equal("Laptop"))
 {
     MasterDal dal = new MasterDal("dbShubertEntitiesCEILaptop");
 }
like image 150
Rohit Kumar Avatar answered Aug 04 '26 10:08

Rohit Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!