Sunday, January 4, 2026

PendingModelChangesWarning Exception When Applying EF Migrations that Involve ASP.NET Core Identity

I have a couple of personal projects that use ASP.NET Identity for user management, and both of them ran into the same problem when running Entity Framework migrations with a dedicated project as shown in the Aspire examples. That is, a Worker Service project that runs the migrations in a BackgroundService.

The error looked like this:

System.InvalidOperationException: 'An error was generated for warning 'Microsoft.EntityFrameworkCore.Migrations.PendingModelChangesWarning': The model for context 'MyContext' has pending changes. Add a new migration before updating the database. See https://aka.ms/efcore-docs-pending-changes. This exception can be suppressed or logged by passing event ID 'RelationalEventId.PendingModelChangesWarning' to the 'ConfigureWarnings' method in 'DbContext.OnConfiguring' or 'AddDbContext'.'

As suggested, I tried generating a new migration, but it was empty. After much AI-assisted debugging, it seemed to be an issue with the length of the columns on a couple of built in tables/classes:
  • IdentityUserToken
    • LoginProvider
    • Name
  • IdentityUserLogin
    • LoginProvider
    • ProviderKey
Some searching suggested that the default lengths of these have changed over the years and that they are adjustable for that reason. I have never specified the lengths in my code, so I don't know how they are being resolved to values different from what's in my DB. And this is only a problem when I run the migrations with the Worker Service project. When run from the command line tool, everything is fine.

As the exception mentions, there is a way to ignore this error, but then it would be ignored for all such future problems where you really forgot to add a migration.

The solution I found is to specify the lengths of the fields in OnModelCreating of my context:

builder.Entity<IdentityUserToken<string>>(entity =>
{
    entity.Property(m => m.LoginProvider).HasMaxLength(128);
    entity.Property(m => m.Name).HasMaxLength(128);
});
 
builder.Entity<IdentityUserLogin<string>>(entity =>
{
    entity.Property(m => m.LoginProvider).HasMaxLength(128);
    entity.Property(m => m.ProviderKey).HasMaxLength(128);
});

No comments:

Post a Comment