Skip to content

Migration classes no longer detected with [DbContext] on base class #37431

@roji

Description

@roji

@AndriySvyryd am not sure if the below was intentional or not, PTAL.

AI summary:

Summary of Findings

The issue is a general EF Core 10 regression affecting all database providers (confirmed on both PostgreSQL and SQL Server). Migrations are no longer discovered if the [DbContext] attribute is placed on a base class rather than the concrete migration class.

###Root Cause
The regression was introduced in EF Core 10.0.0-rc.2 via PR #36666 in the dotnet/efcore repository. This PR was intended to fix Issue #35590, where multiple [DbContext] attributes in an inheritance hierarchy caused an AmbiguousMatchException.

To fix that, the discovery logic in src/EFCore.Relational/Migrations/Internal/MigrationsAssembly.cs was changed to use inherit: false when looking up the DbContextAttribute:

While this prevents the AmbiguousMatchException, it also prevents EF Core from finding the attribute when it is only defined on a base class, which was a supported pattern in EF Core 9.

Minimal repro
using var uow = new UnitOfWork();

var migrations = uow.Database.GetMigrations().ToArray();
Console.WriteLine($"Migrations count: {migrations.Length}");

foreach (var m in migrations)
{
    Console.WriteLine($"- {m}");
}

if (migrations.Length == 0)
{
    throw new Exception("No migrations found!");
}

public class UnitOfWork : DbContext
{
    public DbSet<User> Users => Set<User>();

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder
            .UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=efcore_migrations;Trusted_Connection=True")
            .LogTo(Console.WriteLine, LogLevel.Information);
}

public class User
{
    public Guid Id { get; set; }
}

[DbContext(typeof(UnitOfWork))]
public abstract class MigrationBase : Migration
{
}

[Migration("202512271406_CreateUsers")]
public class Migration_202512271406_CreateUsers : MigrationBase
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.CreateTable(
           name: "Users",
           columns: table => new
           {
               Id = table.Column<Guid>(nullable: false),
           },
           constraints: table =>
           {
               table.PrimaryKey("PK_Users", x => x.Id);
           }
        );
    }
}

Originally reported by @Ryba1986 in npgsql/efcore.pg#3697

Metadata

Metadata

Type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions