Ef Core花里胡哨系列(4) 多租戶(hù)
當(dāng)然,我們要考慮設(shè)計(jì)問(wèn)題,例如,切換
Schema
或者改變數(shù)據(jù)庫(kù)時(shí),Ef Core
同樣也會(huì)刷新改實(shí)體的緩存,所以,首次查詢(xún)將會(huì)很慢,不適合大表。
基于Schema實(shí)現(xiàn)多租戶(hù)
在我的上一篇博客中 [Ef Core花里胡哨系列(3) 動(dòng)態(tài)修改實(shí)體對(duì)應(yīng)的表(分表)、多租戶(hù)]
中我們實(shí)現(xiàn)了如何分表,同理,我們可以用近似的方法來(lái)切換表的Schema
,只需要一點(diǎn)很小的改動(dòng)。
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);
}
}
基于多庫(kù)實(shí)現(xiàn)多租戶(hù)
實(shí)現(xiàn)切換數(shù)據(jù)庫(kù)我們將會(huì)采用的是Interceptor
攔截器來(lái)實(shí)現(xiàn)。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-771903.html
建議租戶(hù)相關(guān)的操作采用單獨(dú)的
DbContext
和系統(tǒng)表區(qū)分開(kāi)。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-771903.html
public class TenantDbConnectionInterceptor<T> : DbConnectionInterceptor
{
public TenantDbConnectionInterceptor()
{
}
public override InterceptionResult ConnectionOpening(DbConnection connection, ConnectionEventData eventData, InterceptionResult result)
{
connection.ConnectionString = "對(duì)應(yīng)租戶(hù)的連接字符串";
return base.ConnectionOpening(connection, eventData, result);
}
public override ValueTask<InterceptionResult> ConnectionOpeningAsync(DbConnection connection, ConnectionEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default)
{
connection.ConnectionString = "對(duì)應(yīng)租戶(hù)的連接字符串";
return base.ConnectionOpeningAsync(connection, eventData, result, cancellationToken);
}
}
使用攔截器
services.AddDbContext<DynamicDbContext>(opts =>
{
opts.AddInterceptors(new TenantDbConnectionInterceptor());
});
到了這里,關(guān)于Ef Core花里胡哨系列(4) 多租戶(hù)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!