How To Change/Switch The Database Dynamically In An ASP.NET MVC Application

This is an example with code snippets to show how to switch or change the database (Connection string) dynamically while running a program in ASP.NET MVC 5 applications.

Introduction

This is an example with code snippets to show how to switch or change the database (Connection string) dynamically while running a program in ASP.NET MVC 5 applications.

Let’s get straight to the task. First off, you need to have more than one databases so as to switch or change between them.

Code snippets

Let’s create a database with name “Database1”.
ASP.NET

Let’s create a table as "AuditTable" with the columns as mentioned.

ASP.NET

Note

Here, I’m switching my databases between PersonDatabase and EmployeeDatabase. Hence I have two columns named PersonID and EmployeeID. (Make sure your PersonID and EmployeeID are different, if not it will create a conflict between the databases.)

You should also need to make sure that the credentials Servername, DatabaseName, UserID and Password of the database to be inserted as and when an entry is made to either PersonTable or EmloyeeTable.

Let’s create tables in each database (PersonDatabase and EmployeeDatabase) with basic information as shown.

  1. Person Table

    ASP.NET

  2. Employee Table

    ASP.NET

So, now we are done with the database creation let’s just move on for some coding. Let’s create a new Empty MVC project from Visual Studio.

ASP.NET

Now, create the .edmx files for the Database1, PersonDatabase, and EmployeeDatabase individually. Since we have created three different .edmx files, we will be having three different connection strings in web.config file.

  1. <connectionStrings>  
  2.     <addname="Database1Entities" connectionString="metadata=res://*/Models.TNEModel.csdl  
  3. |res://*/Models.TNEModel.ssdl|res://*/Models.TNEModel.msl; provider=System.Data.SqlClient;provider connection string="data source='Your Data Source';initial catalog=Database1; ;user id='Your user ID';password='Your Password';integrated security=True; MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />  
  4.     <add name="PersonDatabaseEntities" connectionString="metadata=res://*/Models.PersonModel.csdl|res://*/Models.PersonModel.ssdl|  
  5. res://*/Models.PersonModel.msl;provider=System.Data.SqlClient;provider connection string="data source='Your Data Source';initial catalog='Your Initial Catalog';  
  6. user id='Your user ID';password='Your Password';MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />  
  7.     <add name="EmployeeDatabaseEntities" connectionString="metadata=res://*/Models.EmployeeModel.csdl|res://*/Models.EmployeeModel.ssdl|  
  8. res://*/Models.EmployeeModel.msl;provider=System.Data.SqlClient;provider connection string="data source='Your Data Source';initial catalog='Your Initial Catalog';  
  9. user id='Your user ID';password='Your Password';MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />   
  10. </connectionStrings>  

Replace your datasource with {0}, initialcatalog with {1}, userid with {3}, and password with {4} in your PersonDatabaseEntities and EmployeeDatabaseEntities as shown. So that we can replace them by the one which we need to change or switch.

We now need to configure our connection string so as to get the values of datasource, initialcatalog, userid, and password for our connection strings. For that, we will write a class and fetch the properties from the table of Database1.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Configuration;  
  6. using System.Web.Configuration;  
  7. namespace ConnectionString {  
  8.     public class Connection {  
  9.         public string ConfigurnewConnectionString(string server, string database, string userid, string password, string ConnectionString) {  
  10.             System.Configuration.Configuration Config1 = WebConfigurationManager.OpenWebConfiguration("~");  
  11.             ConnectionStringsSection conSetting = (ConnectionStringsSection) Config1.GetSection("connectionStrings");  
  12.             conSetting.ConnectionStrings[ConnectionString].ConnectionString = conSetting.ConnectionStrings[ConnectionString].ConnectionString.ToString().Replace("{0}", server);  
  13.             conSetting.ConnectionStrings[ConnectionString].ConnectionString = conSetting.ConnectionStrings[ConnectionString].ConnectionString.ToString().Replace("{1}", database);  
  14.             conSetting.ConnectionStrings[ConnectionString].ConnectionString = conSetting.ConnectionStrings[ConnectionString].ConnectionString.ToString().Replace("{2}", userid);  
  15.             conSetting.ConnectionStrings[ConnectionString].ConnectionString = conSetting.ConnectionStrings[ConnectionString].ConnectionString.ToString().Replace("{3}", password);  
  16.             return conSetting.ConnectionStrings[ConnectionString].ConnectionString;  
  17.         }  
  18.     }  
  19. }  

Note: We need to provide the credentials of datasource, initialcatalog, userid, password and name of the connection string to the above class which will replace the {0}, {1}, {2}, {3} of the connection string in web.config file. Refer Controller code for details.

Since we are overwriting the default context.cs class of .edmx file, we are supposed to create a partial class which will overwrite the same as shown.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data.Entity;  
  4. using System.Linq;  
  5. using System.Web;  
  6. namespace ConnectionString.Models {  
  7.     public partial class PersonDatabaseEntities: DbContext {  
  8.         public PersonDatabaseEntities(string Con): base("name=PersonDatabaseEntities") {}  
  9.     }  
  10. }  

Let us now create a Controller with the action method which will access the data from the two different databases.

  1. public ActionResult Index() {  
  2.     try {  
  3.         Database1Entities objDatabase1Entities = new Database1Entities();  
  4.         var obj = objDatabase1Entities.SELECTCONNECTION().FirstOrDefault();  
  5.         Connection objConnection = new Connection();  
  6.         if (obj.DatabaseName == "PersonDatabase") {  
  7.             ConStr = objConnection.ConfigurnewConnectionString(obj.Servername, obj.DatabaseName, obj.UserId, obj.Password, "PersonDatabaseEntities").ToString();  
  8.         } else if (obj.DatabaseName == "EmployeeDatabase") {  
  9.             ConStr = objConnection.ConfigurnewConnectionString(obj.Servername, obj.DatabaseName, obj.UserId, obj.Password, "EmployeeDatabaseEntities").ToString();  
  10.         }  
  11.         // Your Condition to display the data from the desired database  
  12.         return View(obj);  
  13.     } catch (Exception e) {  
  14.         return View("Error");  
  15.     }  
  16. }  

Once you are done with the conditions, you will get the output something like this.

ASP.NET
The above data is from Person database.

ASP.NET
The above data is from Employee database.

Conclusion

Databases can be switched or changed dynamically while running an ASP.NET MVC application. And, we are done.