Hi manvendra45,
Create DBContext with parameterized connection string.
So you can pass connection string before retrieving the data from DBContext.
Check the example.
Model
public class Customer
{
public int CustomerId { get; set; }
public string Name { get; set; }
public string Country { get; set; }
}
DBContext
using Microsoft.EntityFrameworkCore;
public class CustomerDbContext : DbContext
{
public CustomerDbContext(string databaseConnection)
: base()
{
ConnectionString = databaseConnection;
}
public string ConnectionString { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(ConnectionString);
}
public DbSet<Customer> Customers { get; set; }
}
Namespaces
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
Controller
public class HomeController : Controller
{
private IConfiguration Configuration;
public HomeController(IConfiguration _configuration)
{
Configuration = _configuration;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Index(string server)
{
string constr = this.Configuration.GetConnectionString(string.Format("MyConn{0}", server));
return View(this.GetCustomer(constr));
}
public List<Customer> GetCustomer(string connectionString)
{
CustomerDbContext _contextFactory = new CustomerDbContext(connectionString);
return _contextFactory.Customers.ToList();
}
}
View
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@model IEnumerable<Dynamic_Connection_Core_MVC.Models.Customer>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form method="post" asp-controller="Home" asp-action="Index">
<select name="server">
<option value="">Select</option>
<option value="Mumbai">Mumbai</option>
<option value="Delhi">Delhi</option>
</select>
<input type="submit" value="Get Data" />
</form>
@if (Model != null)
{
<hr />
<table id="tblFiles" cellpadding="0" cellspacing="0">
<tr>
<th>Id</th>
<th>Name</th>
<th>Country</th>
</tr>
@foreach (var customer in Model)
{
<tr>
<td>@customer.CustomerId</td>
<td>@customer.Name</td>
<td>@customer.Country</td>
</tr>
}
</table>
}
</body>
</html>
Screenshot