Summary:
This is possible to be done via .HasDefaultSchema() and some configuration injection in your context.
You can see example on GitHub.com.
What is done there:
1) We add schema to app.settings:
"Database": {
"Schema": "test"
},
2) Additional model and provider for schema:
DatabaseSettings.cs
public class DatabaseSettings
{
public string Schema { get; set; }
}
SchemaProvider.cs
public class SchemaProvider : ISchemaProvider
{
private DatabaseSettings Settings { get; }
public SchemaProvider(IOptions<DatabaseSettings> settings)
{
this.Settings = settings.Value;
}
public string GetSchema()
{
return this.Settings.Schema;
}
}
3) In Startup.cs
we register new configuration model and provider for schema name:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<DatabaseSettings>(this.Configuration.GetSection("Database"));
services.Add(new ServiceDescriptor(typeof(ISchemaProvider), typeof(SchemaProvider), ServiceLifetime.Scoped));
var connection = this.Configuration.GetConnectionString("TestDatabase");
services.AddDbContext<TestContext>(options => options.UseSqlServer(connection));
services.AddControllers();
}
4) In TestContext (EF Core Context) we add injection of schema provider and apply selected schema:
public partial class TestContext : DbContext
{
private ISchemaProvider SchemaProvider { get; }
...
public TestContext(DbContextOptions<TestContext> options, ISchemaProvider schemaProvider)
: base(options)
{
this.SchemaProvider = schemaProvider;
}
...
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema(this.SchemaProvider?.GetSchema() ?? "dbo"); // null value supported for migrations from EF Core CLI without application context
...
}
}
What is not done?
This is purely PoC, so this could not be used as production-ready code and requires extensive testing/profiling.
This is not tested against app.settings change on-the-fly and custom configuration loading, there could be different issues.
Migrations are manually fixed to use custom schema. Probably that is possible to support automatic migrations to runtime selected schema, see this link, but I never tried it.