Ef Core花里胡哨系列(4) 多租戶
Ef Core花里胡哨系列(4) 多租戶
當(dāng)然,我們要考慮設(shè)計(jì)問題,例如,切換
Schema或者改變數(shù)據(jù)庫時,Ef Core同樣也會刷新改實(shí)體的緩存,所以,首次查詢將會很慢,不適合大表。
基于Schema實(shí)現(xiàn)多租戶
在我的上一篇博客中 [Ef Core花里胡哨系列(3) 動態(tài)修改實(shí)體對應(yīng)的表(分表)、多租戶] 中我們實(shí)現(xiàn)了如何分表,同理,我們可以用近似的方法來切換表的Schema,只需要一點(diǎn)很小的改動。
public class SampleDbContext(DbContextOptions<SampleDbContext> options)
: DbContext(options)
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().ToTable($"User{DateTime.Now.ToString("yyyyMM")}", YourSchema);
base.OnModelCreating(modelBuilder);
}
}
基于多庫實(shí)現(xiàn)多租戶
實(shí)現(xiàn)切換數(shù)據(jù)庫我們將會采用的是Interceptor攔截器來實(shí)現(xiàn)。
建議租戶相關(guān)的操作采用單獨(dú)的
DbContext和系統(tǒng)表區(qū)分開。
public class TenantDbConnectionInterceptor<T> : DbConnectionInterceptor
{
public TenantDbConnectionInterceptor()
{
}
public override InterceptionResult ConnectionOpening(DbConnection connection, ConnectionEventData eventData, InterceptionResult result)
{
connection.ConnectionString = "對應(yīng)租戶的連接字符串";
return base.ConnectionOpening(connection, eventData, result);
}
public override ValueTask<InterceptionResult> ConnectionOpeningAsync(DbConnection connection, ConnectionEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default)
{
connection.ConnectionString = "對應(yīng)租戶的連接字符串";
return base.ConnectionOpeningAsync(connection, eventData, result, cancellationToken);
}
}
使用攔截器
services.AddDbContext<DynamicDbContext>(opts =>
{
opts.AddInterceptors(new TenantDbConnectionInterceptor());
});

浙公網(wǎng)安備 33010602011771號