Changing the database schema at runtime stopped working after migrating to .NET 6.0 (to .NET 5.0 - everything worked). Please advise how to solve this problem. DBMS - PostgreSQL, ORM - Entity Framework.
For each project in the developed system, there is a separate schema in the database. Sending an HTTP request to the server switches to the correct project schema to interact with the project data. Runtime switching has now stopped working, the schema is only changed when the very first request is sent after the application starts.
I'm using the ModelCacheKeyFactory interface override approach.
MultiTenantModelCacheKeyFactory.cs:
public class MultiTenantModelCacheKeyFactory : ModelCacheKeyFactory
{
private string _schemaName = null!;
public MultiTenantModelCacheKeyFactory(ModelCacheKeyFactoryDependencies dependencies) : base(dependencies)
{
}
public override object Create(DbContext context)
{
if (context is ProjectDatabaseContext dataContext)
{
_schemaName = dataContext.SchemaName;
}
return new MultiTenantModelCacheKey(_schemaName, context);
}
}
MultiTenantModelCacheKey .cs:
public class MultiTenantModelCacheKey : ModelCacheKey
{
private readonly string _schemaName;
public MultiTenantModelCacheKey(string schemaName, DbContext context) : base(context)
{
_schemaName = schemaName;
}
public override int GetHashCode()
{
return _schemaName.GetHashCode();
}
}
Startup.cs:
services.Replace(ServiceDescriptor.Singleton<IModelCacheKeyFactory, MultiTenantModelCacheKeyFactory>());
MyDatabaseContext.cs:
public sealed class MyDatabaseContext: DbContext
{
...
public string SchemaName { get; }
public MyDatabaseContext(ISchemaProviderService schemaProviderService,
DbContextOptions<MyDatabaseContext> options)
: base(options)
{
SchemaName = Task.Run(schemaProviderService.GetSchemaName).Result;
Task.Run(CreateSchemaIfNotExists).Wait();
}
...
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.HasDefaultSchema(SchemaName);
}
private async Task CreateSchemaIfNotExists()
{
...
}
}
Please tell me how to solve my problem.