Skip to content

Changing schema in DbContext without running migrations #37044

@Dersei

Description

@Dersei

Question

For a long time, my project used modelBuilder.HasDefaultSchema("dbo") within the DbContext to set the database schema. However, a new requirement emerged to add support for custom schemas. This involved changing the migrations to accept a schema name and removing the HasDefaultSchema call from the DbContext. This part works fine - migrations run successfully, and tables are created in the specified schema.

The problem is that subsequent connections still use the database's default schema. The solution is to reintroduce HasDefaultSchema, making sure the schema name can be dynamic. The issue with this approach is that the snapshot used for migrations (where the schema is not defined) no longer matches the DbContext configuration. As a result, EF Core requires me to add a new, unnecessary migration.

Is there a way to define the schema for the DbContext in such a way that it doesn't trigger the need for a new migration? Or perhaps there's another way to solve this problem?

Your code

Stack traces


Verbose output


EF Core version

9.0.9

Database provider

Microsoft.EntityFrameworkCore.SqlServer

Target framework

.NET 9.0

Operating system

Windows 11

IDE

Jetbrains Rider

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions