I am working on multi layered architecture with supporting multiple database per tenant in MVC. I need to create DBContext depending on the user logged in into data layer. How should I create generic DBContext and set connection string according to user?
Following is code to get connection string from Host Databsae and set it to Client Database. (In data/repository layer)
private static string GetConnectionString()
{
int tenantId;
HostDBContext hostContext = new HostDBContext();
//Get Tenant and set ID to get required connection string
tenantId = 1; //Get Tenant Id from session
var tenantDetails = hostContext.TenantDetails.Find(tenantId);
if (tenantDetails != null)
{
return tenantDetails.connectionstring;
}
return "default connection string";
}