[英]Create DbContext dynamically for multiple database architecture with repect to logged-in user
I am working on multi layered architecture with supporting multiple database per tenant in MVC. 我正在研究多层体系结构,在MVC中每个租户支持多个数据库。 I need to create DBContext depending on the user logged in into data layer.
我需要根据登录到数据层的用户来创建DBContext。 How should I create generic DBContext and set connection string according to user?
如何创建通用DBContext并根据用户设置连接字符串?
Following is code to get connection string from Host Databsae and set it to Client Database. 以下是从Host Databsae获取连接字符串并将其设置为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";
}
You're on the right track, but it won't be a generic DbContext
, just one that with a connection string that's set at runtime. 您
DbContext
正确的轨道上,但这不是通用的 DbContext
,而只是一个在运行时设置了连接字符串的DbContext
。 So instead of GetConnectionString, you want to create a DbContext
factory that requires the tenant Id to return your new DbContext("connectionString"). 因此,您要创建一个
DbContext
工厂而不是GetConnectionString,该工厂要求租户ID返回新的DbContext(“ connectionString”)。
Let's call it TenantDbContext
: 我们称之为
TenantDbContext
:
public class TenantDbContext : DbContext
{
public TenantDbContext(string connectionString) : base(connectionString)
{
}
// Or
public TenantDbContext(int tenantId) : base(GetConnectionString(tenantId))
{
}
}
if using a factory: 如果使用工厂:
public class TenantDbContextFactory : IDbContextFactory<TenantDbContext, int>
{
public TenantDbContext Create(int tenantId)
{
var connectionString = GetConnectionString(tenantId);
return new TenantDbContext(connectionString);
}
// ... rest of factory
}
public interface IDbContextFactory<TContext, TKey> where TContext :DbContext
{
TContext Create(TKey key);
}
If you're using a dependency injection container, you can also wire it up to return the TenantDbContext
based on the tenant Id. 如果您使用的是依赖项注入容器,则还可以将其连接起来以根据租户ID返回
TenantDbContext
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.