-
Notifications
You must be signed in to change notification settings - Fork 19
Changing default schema at runtime
Changes the default schema of the DbContext and its Migrations at runtime.
The DbContext has to implement the interface IDbDefaultSchema. The interface provides a new property Schema of type string.
public class DemoDbContext : DbContext, IDbDefaultSchema
{
public string Schema { get; }
public DemoDbContext(DbContextOptions<DemoDbContext> options, IDbDefaultSchema schema = null)
: base(options)
{
Schema = schema?.Schema;
}Remarks: Setting the
Schemain constructor by injecting an instance ofIDbDefaultSchemais just an example. You can set theSchemain any way you want.
Use extension method AddSchemaRespectingComponents to register some components so EF "knows" about IDbDefaultSchema.
ServiceCollection services = ...;
services
.AddDbContext<DemoDbContext>(builder => builder
//.UseSqlite("...")
.UseSqlServer("...")
...
.AddSchemaRespectingComponents());An instance of IDbDefaultSchema can (but don't have to) be injected into migration if some operations (like raw SQL) have to know the schema.
public partial class MyMigration : Migration
{
public MyMigration(IDbDefaultSchema schema)
{
}
...
}The IDbDefaultSchema has no effect on the migration history table. Use the EF method MigrationsHistoryTable to change the table name and schema.
ServiceCollection services = ...;
services
.AddDbContext<DemoDbContext>(builder => builder
.UseSqlServer("conn-string", sqlOptions =>
{
if (schema != null)
sqlOptions.MigrationsHistoryTable("__EFMigrationsHistory", schema);
})
...For the change of the schema at runtime we have to decorate some EF Core components. The decoration of the components is done via AddSchemaRespectingComponents.
Following components are decorated:
-
IModelCustomizerbyDefaultSchemaModelCustomizer -
IModelCacheKeyFactorybyDefaultSchemaRespectingModelCacheKeyFactory -
IMigrationsAssemblybyDefaultSchemaRespectingMigrationAssembly
- Collection Parameters (temp-tables light) (SQL Server)
- Window Functions Support (RowNumber, Sum, Average, Min, Max)
- Nested (virtual) Transactions
- Table Hints (SQL Server)
- Queries accross multiple databases (SQL Server)
- Changing default schema at runtime
- If-Exists / If-Not-Exists checks in migrations (SQL Server)
- Migrations: include-columns (SQL Server)
- Migrations: identity column (SQL Server)
- Migrations: (non-)clustered PK (SQL Server)