多租户多数据库,具有代码第一个EF 6和ASP.Net MVC 4 [英] Multi Database for Multi Tenant with Code first EF 6 and ASP.Net MVC 4
问题描述
我正在构建一个SAAS应用程序,并为每个客户端计划一个数据库。我正在使用ASP.NET MVC 4的Code First EF6。
I am building a SAAS application and planned for one database per client. I am using Code First EF6 with ASP.Net MVC 4.
将有2个上下文,即MasterContext和TenantContext。用户将首先访问MasterContext以验证用户凭据并获取其租户配置。
There will be 2 context i.e. MasterContext and TenantContext. User will first hit to MasterContext to authenticate user credentials and fetch its Tenant configuration.
基于获取的租户配置; TenantContext设置为Tenant特定数据库,并用于租户CRUD操作。
Based on fetched Tenant configuration; TenantContext is set to Tenant specific database and used for Tenant CRUD operations.
请咨询如何实现。
推荐答案
想法是识别当前的请求tenant_id并使用它来获取数据库配置,并创建如下代码的DbContext。
The idea is to identify the current request tenant_id and use that to fetch the database configuration and create DbContext like the below code.
public AppDbContext : DbContext
{
private const string _defaultCS = "default app connection string";
public AppDbContext() : base(GetConnectionString())
{
}
private string GetConnectionString()
{
return TenantContext.ConnectionString ?? _defaultCS;
}
}
样本用法
public class StudentRepo
{
public Student Get(Guid id)
{
using(var ctx = new AppDbContext())
{
return ctx.Students.FirstOrDefault(x=>x.Id == id);
}
}
}
这将自动连接到登录租户数据库。
This will automatically connect to the logged in tenant database.
您可能需要在Auth Cookie中存储tenant_id,并在PostAuthenticate_Event之后读取,并存储在HttpContext.Current.Items中
You might need to store tenant_id in Auth cookie and read it after PostAuthenticate_Event and store in HttpContext.Current.Items
public static TenantContext
{
public static Guid TenantId
{
get
{
return (Guid)HttpContext.Current.Items["__TenantID"];
}
}
public static string ConnectionString
{
get
{
return TenantConfigService.GetConnectionString(TenantId);
}
}
}
在一些HTTP模块Init方法
In some HTTP module Init method
context.PostAuthenticateRequest += context_PostAuthenticateRequest;
void context_PostAuthenticateRequest(object sender, EventArgs e)
{
FormsIdentity identity = Thread.CurrentPrincipal.Identity as FormsIdentity;
if (identity != null)
{
HttpContext.Current.Items["__TenantID"] = GetTenantIdFromTicket(identity.Ticket.UserData); // returns tenant_id as guid type
}
}
这篇关于多租户多数据库,具有代码第一个EF 6和ASP.Net MVC 4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!