Skip to content

How to connect to multi-database in using ASP MVC 5

Posted in Education, and WhoCodeFirst

You can connect to multiple databases by creating separate connections and contexts for each database.

Here’s an example of how you can set up multiple database connections in your C#/ASP project:

In your web.config file, define the connection strings for each database. For example:

<connectionStrings>   
<add name="Db1" connectionString="Data Source=server1;Initial Catalog=db1;User ID=user1;Password=password1" providerName="System.Data.SqlClient" />   
<add name="Db2" connectionString="Data Source=server2;Initial Catalog=db2;User ID=user2;Password=password2" providerName="System.Data.SqlClient" /> </connectionStrings> 

In your DbContext class, create a constructor that takes a connection string name as a parameter. For example:

public class MyDbContext : DbContext
 {
     public MyDbContext(string connectionString) : base(connectionString) { }
     //…
 }

In your controller or service, create an instance of the DbContext class for each connection string you want to use. For example:

 public class MyController : Controller 
{    
 private readonly MyDbContext _db1;    
 private readonly MyDbContext _db2;    
 public MyController() {       
  _db1 = new MyDbContext("Db1");       
  _db2 = new MyDbContext("Db2");}    
 //...
} 

Use the appropriate DbContext instance for each database operation. For example:

 public ActionResult Index() {   
  var data1 = _db1.MyEntities.ToList();    
  var data2 = _db2.MyEntities.ToList();    
 //... } 

This is a basic example of how you can set up multiple database connections in ASP.NET MVC 5. Depending on your specific needs, you may need to add additional logic to handle database errors, transactions, or other advanced features.

You can also use dependency injection to manage the multiple DbContext and use it in your controllers or services.

The above code is just an example, you might need to make some adjustments to fit your specific use case.

Happy Learning!

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *