Skip to content

Changing default schema at runtime

Pawel Gerr edited this page Nov 16, 2026 · 5 revisions

Required Nuget Package: Thinktecture.EntityFrameworkCore.Relational

Changes the default schema of the DbContext and its Migrations at runtime. Works with all supported providers (SQL Server, PostgreSQL, MySQL, SQLite).

Note: SQLite has no concept of schemas, so the components are wired up but the feature has no practical effect there. It is meaningful on SQL Server and PostgreSQL.

Note: MySQL has no schemas either. The MySQL provider handles a schema of the model according to its option SchemaBehavior: MySqlSchemaBehavior.Throw (the default) rejects a schema, Ignore drops it, and Translate maps it into the table name. With Throw, the bulk operations, TruncateTableAsync and the query-based bulk operations of this library throw a NotSupportedException for a table with a schema, because the statement would otherwise address the current database. On MySQL, the schema changes the generated table names only with SchemaBehavior Translate, for example with the translator (schema, table) => $"{schema}_{table}". This combination is not covered by the tests of this library.

Usage

1. Implement IDbDefaultSchema

The DbContext has to implement the interface IDbDefaultSchema. The interface provides a new property Schema of type string? (nullable; null means the provider default schema, e.g. dbo/public).

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 Schema in constructor by injecting an instance of IDbDefaultSchema is just an example. You can set the Schema in any way you want.

2. Register Components

Use extension method AddSchemaRespectingComponents to register some components so EF "knows" about IDbDefaultSchema.

ServiceCollection services = ...;

services
   .AddDbContext<DemoDbContext>(builder => builder
                                              //.UseSqlite("...")
                                              .UseSqlServer("...")
                                              //.UseNpgsql("...")
                                              ...
                                              .AddSchemaRespectingComponents());

3. (Optional) Using default schema in migrations

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)
   {
   }

   ...
}

4. (Optional) Changing schema of MigrationsHistoryTable

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
          // SQL Server
          .UseSqlServer("conn-string", sqlOptions =>
                                      {
                                         if (schema != null)
                                            sqlOptions.MigrationsHistoryTable("__EFMigrationsHistory", schema);
                                       })
          // PostgreSQL
          //.UseNpgsql("conn-string", npgsqlOptions =>
          //                          {
          //                             if (schema != null)
          //                                npgsqlOptions.MigrationsHistoryTable("__EFMigrationsHistory", schema);
          //                          })
    ...

Remarks

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:

  • IModelCustomizer by DefaultSchemaModelCustomizer
  • IModelCacheKeyFactory by DefaultSchemaRespectingModelCacheKeyFactory
  • IMigrationsAssembly by DefaultSchemaRespectingMigrationAssembly

Clone this wiki locally