我正在使用多租户应用程序,其中每个用户都有不同的数据库架构。
根据用户凭据,我们将获得他所属的架构。
下面是我的上下文类,它每次根据schemaName动态刷新上下文
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public string SchemaName { get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public ApplicationDbContext(string schemaname)
: base()
{
SchemaName = schemaname;
}
public DbSet<EmployeeDetail> EmployeeDetail { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
var configuration = builder.Build();
var serviceProvider = new ServiceCollection().AddEntityFrameworkSqlServer()
.AddSingleton<IModelCustomizer, SchemaContextCustomize>()
.BuildServiceProvider();
optionsBuilder.UseSqlServer(configuration["ConnectionStrings:SchemaDBConnection"]).UseInternalServiceProvider(serviceProvider);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// modelBuilder.MapProduct(SchemaName);
modelBuilder.RemovePluralizingTableNameConvention();
if (!string.IsNullOrEmpty(SchemaName))
{
modelBuilder.HasDefaultSchema(SchemaName);
}
base.OnModelCreating(modelBuilder);
}
public string CacheKey
{
get { return SchemaName; }
}
public class SchemaContextCustomize : ModelCustomizer
{
public SchemaContextCustomize(ModelCustomizerDependencies dependencies)
: base(dependencies)
{
}
public override void Customize(ModelBuilder modelBuilder, DbContext dbContext)
{
base.Customize(modelBuilder, dbContext);
string schemaName = (dbContext as ApplicationDbContext).SchemaName;
(dbContext as ApplicationDbContext).SchemaName = schemaName;
}
}
以上代码可完美运行,没有任何问题。 OnConfiguring
方法负责每次提供正确的架构
与性能相关的主要问题是因为每次请求以下行初始化上下文都需要花费近40%的时间
base.Customize(modelBuilder, dbContext);
有什么方法可以提高性能,理想情况下应该调用一次。
在运行时基于用户更改架构以使OnConfiguring方法仅被调用一次的正确方法是什么?