Skip to content

Background and information around the 9.0 PendingModelChangesWarning error #35285

Closed as not planned

Description

@roji

Everyone, we know some of you are (understandably) frustrated by the new PendingModelChangesWarning error that gets thrown when upgrading to EF 9. I wanted to share some information on the new error, why we did it and what you should do about it.

The main motivation behind this change was something that happens often: you make some change to your model (e.g. add a property), and then you forget to actually add a migration to apply it to the database. You run MigrateAsync() (or similar) and can't figure out why your database hasn't been updated; the new error clearly tells you that your model contains changes with respect to the last migration snapshot. In other words, the point here is to help you avoid accidental error.

Now, there are some other cases where this error is thrown, even if you haven't done any changes; code that seemed to run just fine in EF 8 suddenly starts throwing in EF 9. A lot of people have assumed that this is a problem in EF, but in reality the error usually still indicates some problem in your code that was there before, but was not flagged. That's a good thing! Even here, the point is to help you clean up the problem and avoid problems. Of course, you always have the option of simply suppressing the warning (see below), so you should never be blocked for upgrading to EF 9; it's fine to do this temporarily, and then maybe come back and deal with it later, after upgrading, once you have more time to focus on it.

Here's an example: some people want to seed their database with some random Guids, so they put code such as the following in their model configuration:

modelBuilder.Entity<Blog>().HasData(new Blog { Id = Guid.NewGuid(), ... });

This looks simple enough, but it's actually quite problematic. For each migration, EF stores a snapshot of your model for that migration. When you create a new migration, EF compares your current model (represented by your code) with the latest snapshot, and the new migration represents the difference between these two. In 9.0, when you call MigrateAsync, EF does the exact same thing, and if any changes are detected, throws the new PendingModelChangesWarning error.

Now, when you generated your last migration, Guid.NewGuid() got evaluated at that point, and an actual random Guid gets integrated into the previous context snapshot; you can open up the XXXContextModelSnapshot.cs in your migrations directory, and see that Guid. Now, when you call MigrateAsync, Guid.NewGuid() gets evaluated again, but because the random Guid it generates will differ from the one stored in the model snapshot, EF detects this as a pending model change (as if you forgot to add a migration!).

The solution to this is very simple: avoid using dynamic (or non-deterministic) APIs such as Guid.NewGuid(), and embed specific GUIDs instead:

modelBuilder.Entity<Blog>().HasData(new Blog { Id = Guid.Parse("9e4f49fe-0786-44c6-9061-53d2aa84fab3"), ... });

Once you do this, generate a new migration once, and this whole thing will be behind you.

Why is this important? Previous versions of EF may have not thrown PendingModelChangesWarning for this, but they also didn't work well around this situation. For example, every time you added a migration, EF would see a model change in the Guid seed data, and generate a useless migration to change that value in the database - that's a bad state of affairs that the new error helps detect and fix. So while the new error is frustrating, it's there to help you get your code in better shape.

There are some other cases where this error will be thrown; we've recently published a breaking change note listing these, and explaining what to do. Also, since the error has been causing some confusion, we recently merged an improvement that will be released in 9.0.1: EF will now recognize some of the issues causing the "pending model changes" error, and throw more specific errors to let you know exactly what the problem is. For example, the case above with Guid.NewGuid() will now be detected, and we'll tell you that you're using dynamic values in HasData.

Another source of these warning is ASP.NET Core Identity if you change the defaults, something like:

services.AddDefaultIdentity<ApplicationUser>(options =>
    {
        options.Stores.SchemaVersion = IdentitySchemaVersions.Version2;
        options.SignIn.RequireConfirmedAccount = false;
    })
    .AddRoles<IdentityRole>()
    .AddEntityFrameworkStores<DatabaseContext>();

This configuration will not be picked up by the EF tools unless you specify the app as the startup project. Alternatively, you can implement IDesignTimeDbContextFactory.

If you are using an implementation of IDesignTimeServices make sure that it's referenced from the migrations project:

[assembly: DesignTimeServicesReference("YourNamespace.YourDesignTimeServices")]

Hopefully the above clarifies things; we recommend looking into it and trying to fix the root cause - this way you end up with a better, more stable application. But if you choose to, you can suppress the warning, and revert back to the same situation as in previous versions of EF:

options.ConfigureWarnings(w => w.Ignore(RelationalEventId.PendingModelChangesWarning))

Activity

  1. self-assigned this
    on Dec 6, 2024
  2. added this to the Discussions milestone on Dec 7, 2024
  3. pdevito3 commented on Dec 7, 2024

    @pdevito3

    I appreciate the clarity and get the desire here to try and help. This error probably will help people new to EF too, but at the very least something here seems off in something like my use case.

    As far as i knew, I had no dynamic or non-deterministic APIs. All of my migrations are straight EF generated with zero migration modifications and no HasData usages or other seeds. The closest I have to this is is my BaseEntity (entity, not in a migration) having a default for the id prop of NewGuid():

    public abstract class BaseEntity
    {
        [Key]
        public Guid Id { get; private set; } = Guid.NewGuid();
        //...
    }
    

    From what i saw in the original ticket this is somehow getting picked up, but I know of no no other way to do this in code and not doing so would be bad dx as id's would show as empty guids until save. I don't see this showing up in my snapshot either.

    Is there an alternative you guys recommend? Or are we just supposed to live with a bad dx here or add explicit code that overrides this error?

  4. roji commented on Dec 7, 2024

    @roji
    MemberAuthor

    @pdevito3 yeah, initializing your property to a Guid property on your CLR type in this way is effectively the same as including it inside HasData(): every time the model runs, the seeding data that's included in the model has a different Guid (since your HasData has a new MyEntity() in it, which causes a new Guid to get generated).

    To fix this, you can:

    • Make your Id setter public, and set it explicitly to some value within HasData()
    • If you don't want to make the setter public, you can switch to using an anonymous type inside HasData(). For example, instead of having HasData(new MyEntity { Foo = "..." }), you can have HasData(new { Id = Guid.Parse("..."), Foo = "..." }). This would restrict to change to your HasData() configuration, without impacting what your CLR type looks like.
  5. ajcvickers commented on Dec 7, 2024

    @ajcvickers
    Contributor

    @roji I think @pdevito3 is saying they have no calls to HasData:

    with zero migration modifications and no HasData usages or other seeds.

  6. rudiv commented on Dec 7, 2024

    @rudiv

    I'm glad the breaking change note is there now (there needs to be one for temporal migrations too #35108 as it's impossible to upgrade if you use them).

    Agree with @pdevito3 that this is great for new developers to know what's going on and why their code is throwing errors at runtime, but I don't understand why this isn't handled better and with correct terminology.

    the new PendingModelChangesWarning error

    Is it actually meant to be a warning or an error? If it truly was a warning, that yellow log printing to the console on build would be extremely helpful so that we know we need to do something. It could also throw as an error at the time when it would actually cause the runtime exception rather than being an ambiguous "column not found" (or similar) error. The current behaviour of having it exploding vs not having it at all is worse.

    Typically on larger changes to models, for example either early stages where the data structure needs to change to support what is being built out, or later stages where an entire model is being changed, we want to be actively on the system whilst simultaneously updating code for the models until we get the result that we desire. To do this now, we'd have to disable warnings, rebuild, incrementally make our changes, and then migrate and put the warning back in.

    #35221 seems to be a step in the right direction where certain types of the same warning won't throw an exception which is awesome! But the use case above as far as I can see is still going to throw an exception by default? I may be being stupid as I've only had a cursory look at the PR.

    Surely it would be better to have multiple types of "warnings" so that we can suppress them individually rather than all on and off?

  7. pdevito3 commented on Dec 7, 2024

    @pdevito3

    @roji I think @pdevito3 is saying they have no calls to HasData:

    with zero migration modifications and no HasData usages or other seeds.

    Correct. This is in my base entity model that all my dbsets inherit from. This default makes it so my entities get an actual id value when created in code instead of waiting for save changes to do it for me. Without a default guid like this, the id is always empty until save. I had this in a project once and it was very much bad dx.

  8. roji commented on Dec 7, 2024

    @roji
    MemberAuthor

    @ajcvickers @pdevito3 sorry, I missed that important sentence :) In that case @pdevito3 it would be good to have a repro, to make sure this isn't some case we're not aware of... If you can put that together, can you please open a new issue containing that repro?

  9. roji commented on Dec 7, 2024

    @roji
    MemberAuthor

    @rudiv

    Is it actually meant to be a warning or an error?

    EF events such as this can be configured by the user to be errors (throw an exception), be a warning (log), or completely ignored. This specific event is handled as an error by default, which is why it's throwing an exception for people (but can be ignored).

    Typically on larger changes to models, for example either early stages where the data structure needs to change to support what is being built out, or later stages where an entire model is being changed, we want to be actively on the system whilst simultaneously updating code for the models until we get the result that we desire. To do this now, we'd have to disable warnings, rebuild, incrementally make our changes, and then migrate and put the warning back in.

    I don't follow this. All this error does, is throw when you attempt to call MigrateAsync (or similar) and haven't yet added the appropriate migration to represent your later changes. You can make changes to the model and even run your application as long as you don't try to call migrate (your database would then represent a different schema than what your application expects); you can also make changes to the model and add the appropriate migration (that's the normal/expected flow). But I don't ese how it makes sense to change your model and then calling MigrateAsync, without also adding the migration to account for thoes model changes.

  10. rudiv commented on Dec 7, 2024

    @rudiv

    It may just be me @roji but after far too many years of working with EF without this exception, and in dev having MigrateAsync() in the startup for dev to keep things always in sync, we could be going through the app to make changes with it running and making changes to the models whilst we're running in dev mode.

    The issue now is that when we make 1 (of N) changes and save that model, alongside dotnet watch (a typical dev loop) the application will stop running as an exception is thrown at startup.

  11. pdevito3 commented on Dec 7, 2024

    @pdevito3

    If you can put that together, can you please open a new issue containing that repro?

    @roji I just took a quick stab at this and from what i can tell so far having a base entity with a default like public Guid Id { get; private set; } = Guid.NewGuid(); does NOT seem to trigger the error after a .NET 9 upgrade like has been assumed previously.... with that said, I stand by the fact that my actual project has no HasData usages, migration mods, or other areas that i can tell are using dynamic or non-deterministic APIs and it does still run into this issue.

    I can continue trying to narrow down a repro and open a ticket if I find it, but this does speak to what has been brought up about a specific callout about what change was found so we can target the issue instead of hunting or slapping an ignore on would be great. I know the errors have been enhanced a bit but if they don't get to that level of detail, there's still a gap to fill i think

  12. elementum commented on Dec 23, 2024

    @elementum

    Having same problem here, I have no dynamic data and no calls to HasData. Adding new migration results in empty migration.
    I was able to drill into the diff process.

    Consider following entity:

    public class HandledEvent : BaseEntity
    {
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
    
    ... other unrelated members
    }
    

    StartDate and EndDate are not configured explicitly and have default DateTime configuration.

    EF detects following changes in these columns:
    Image

    Can you spot problems here? Any idea how to fix that?

    I'm running Npgsql.EntityFrameworkCore.PostgreSQL 9.0.1

  13. 39 remaining items

  14. cjorgens79 commented on Jul 18, 2025

    @cjorgens79

    I too have pulling my hair out for a fair few hours now over this issue which has come up after migrating to .net 9. In my case I am migrating an old Xamarin Forms project over to MAUI 9.

    My database models were incredibly simple and didn't use any of the things mentioned above, but i was still getting this error and attempting to generate new migrations always resulted in empty migrations, but at runtime I still always got the exception. After great difficultly I have now finally managed to track down the cause so I am posting here in the hope it will save someone else some pain :)

    In my case, my sqlite database model had a field that looks like this

    [StringLength(64)]
    public string RowHash { get; set; }
    

    My snapshot looked like this

    b.Property<string>("RowHash ")
        .HasMaxLength(64)
        .HasColumnType("TEXT");
    

    The problem turns out to be that my existing migrations project that i use to create the migrations (because i cant do it directly in MAUI) was NOT using nullable strings and the MAUI project was. Therefore the RowHash field in the migrations project was interpreted differently to the RowHash field in the MAUI project because of the project's project setting. So ensuring they both have the same project setting meant i could now see the changes which were due to the old xamarin forms project (which was pre nullable strings) defining "public string RowHash" instead of the required "public string? RowHash" in the new project. So in the new nullable project, using string? instead of string for nullable string fields meant it matches the original snapshot definition.

    The only way I managed to figure out what was going on was to generate a new snapshot at runtime and compare it with the expected snapshot to see what the differences were. It then told me which fields were incorrect and lead me to figuring out the problem. For anyone that needs help figuring out what fields are specifically causing the issue, the below can be used to track it down.

    Add the EntityFrameworkCore.Design package into your project (as below), you need this to resolve the snapshots at runtime.
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.6" />

    Copy this "DbInitializer" class into your project

    // DbInitializer.cs
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.EntityFrameworkCore.Infrastructure;
    using Microsoft.EntityFrameworkCore.Migrations;
    using Microsoft.EntityFrameworkCore.Migrations.Operations;
    using Microsoft.Extensions.DependencyInjection;
    using YourApp.Data.Migrations;    // ← where ContextModelSnapshot lives
    
    public class DbInitializer
    {
        private readonly MyDBContext _ctx;
    
        public DbInitializer(MyDBContext ctx)
        {
            _ctx = ctx;
        }
    
        public void DumpPendingChanges()
        {
            // 1. Get EF Core’s internal service provider
            var internalServices = ((IInfrastructure<IServiceProvider>)_ctx).Instance;
    
            // 2. Resolve the services we need
            var modelInitializer = internalServices.GetRequiredService<IModelRuntimeInitializer>();
            var differ           = internalServices.GetRequiredService<IMigrationsModelDiffer>();
            var designTimeModel  = internalServices.GetRequiredService<IDesignTimeModel>().Model;
    
            // 3. Finalize the design-time model & your snapshot
            var finalizedLive     = modelInitializer.Initialize(designTimeModel);
            var snapshotRaw       = new MyDBContextModelSnapshot().Model;
            var finalizedSnapshot = modelInitializer.Initialize(snapshotRaw);
    
            // 4. Build the relational models
            var relationalLive     = finalizedLive.GetRelationalModel();
            var relationalSnapshot = finalizedSnapshot.GetRelationalModel();
    
            // 5. Compute the diff
            IReadOnlyList<MigrationOperation> ops = differ.GetDifferences(relationalSnapshot, relationalLive);
    
            // 6. Dump to Debug
            Debug.WriteLine("=== EF Core PendingModelChanges Diff ===");
            if (ops.Count == 0)
            {
                Debug.WriteLine("✅ No pending operations — snapshot and model match.");
            }
            else
            {
                foreach (var op in ops)
                    Debug.WriteLine($"• {op.GetType().Name}: {op}");
            }
        }
    }
    

    Then wire it up to your DI service, for example

    builder.Services.AddDbContext<MyDBContext>(opts =>
        opts.UseSqlite($"Filename={dbPath}", sql => sql.MigrationsAssembly(typeof(MyDBContext).Assembly.FullName)));
    
    builder.Services.AddScoped<DbInitializer>();
    
    

    Then make use of it in your startup (or elsewhere before you try migrate the context), for example

    ...
    var app = builder.Build();
    
    // dump the snapshot differences
    var init = app.Services.GetRequiredService<DbInitializer>();
    init.DumpPendingChanges();
    
    return app;
    
    

    It will log to the Output -> Debug window any differences, or just put a breakpoint in the DumpPendingChanges function and look at the ops result of the differ.GetDifferences call.

    Note: The above was wired into a MAUI project, it should work for other projects too, but may require minor modifications.

  15. Tjorbenn commented on Aug 6, 2025

    @Tjorbenn

    Hi everyone,

    Just wanted to post a walkthrough of my experience getting an automated EF Core migration service working, because it was quite a journey. Hopefully, this saves someone else a headache.

    My setup is a .NET 10 Preview project using Aspire with PostgreSQL and ASP.NET Core Identity. I started by following the official Microsoft guide on setting up a MigrationService worker because I wanted to automate migrations on startup.

    This was when I ran into the PendingModelChangesWarning, even though I hadn't changed my models, which brought me here. After some digging (which took way too long) I found out this was probably because the full ASP.NET Core Identity setup (AddIdentityCore) configures the DbContext in subtle ways, and the dotnet ef tool wasn't seeing that full configuration.

    So, next I tried to implement an IDesignTimeDbContextFactory, which was proposed here as the standard way to solve that "pending changes" issue. I tried to create a factory that would set up a temporary DI container with the full Identity configuration. This path got really complicated quickly. In an Aspire project, the connection string is provided at runtime by the AppHost, but the design-time factory has no access to that. I tried setting up local connection strings in appsettings.json, but it felt like I was fighting the Aspire model of dynamic configuration and I couldn't get it working smoothly.

    I decided to pivot away from the CLI tools and the factory entirely and go back to the original goal: a worker service that runs MigrateAsync() on startup, just like the guide suggested. This time, I shared my full database and Identity setup from my Blazor WebApp into the MigrationService. This solved the "pending changes" problem, but immediately led to a new crash.

    The service now failed on startup since the MigrationService was Unable to resolve service for type 'IDataProtectionProvider'. It finally clicked that the MigrationService host (using Host.CreateApplicationBuilder) doesn't have all the web-specific services that the full WebApp host does. The problem was that my shared Identity setup was trying to register runtime features like .AddDefaultTokenProviders() and .AddSignInManager(), which the worker service didn't need and couldn't support (which I did not know before).

    The real issue was that my worker needed only parts of that Identity setup: it needs to know the schema (so it can build the migration correctly), but it doesn't need the runtime features (like signing users in).

    The final solution that finally worked was to split the Identity configuration. I created a shared extension method, but made it "lean" so it only registers the bare essentials. The trick was to have it return the IdentityBuilder so I could add to it later in my WebApp.

    My shared method in DatabaseSetup.cs now looks like this:

    // This method just sets up the DB schema and returns the builder
    public static IdentityBuilder AddPersistenceServices(this IHostApplicationBuilder builder)
    {
        builder.AddNpgsqlDbContext<ApplicationDbContext>("Database");
    
        return builder.Services.AddIdentityCore<ApplicationUser>(options =>
            {
                // ... your options
            })
            .AddEntityFrameworkStores<ApplicationDbContext>();
    }

    This enabled a really clean setup in my WebApp's Program.cs where I just chain the web-specific stuff onto the end:

    // In my WebApp's Program.cs
    builder.AddPersistenceServices() // Gets the base schema
        .AddSignInManager()          // Adds the runtime features
        .AddDefaultTokenProviders();

    And the MigrationService Program.cs just has the one simple call to AddPersistenceServices(). It gets the schema info it needs, and nothing more.

    Now it finally works!!! The MigrationService starts, applies migrations to my database, and shuts down. Anyway, it was quite a journey from the initial guide... Hope this story helps understand the different pieces and can save some time :)

  16. AndriySvyryd commented on Aug 6, 2025

    @AndriySvyryd
    Member

    @Tjorbenn Thanks for sharing your experience, I filed dotnet/AspNetCore.Docs#35825 to improve Identity documentation around the EF integration.

  17. Cellcote commented on Sep 25, 2025

    @Cellcote

    We tried updating to EF9 and also ran into the problem. Interestingly, our application was fine, but our unit tests were running to the PendingModelChangesWarning error. Using @cjorgens79 approach we kind of found out what the problem is. In the main code base, we use EF schemaless, which also means that our ModelSnaphot does not have a default schema. In our unit tests, we generate a schema per test fixture, and then use the migrations on that schema. In EF8, this worked fine, but in EF9 we get this new error.

  18. khteh commented on Dec 12, 2025

    @khteh

    I have the following code snippet in Program.cs:

        var identityBuilder = builder.Services.AddIdentityCore<AppUser>(o =>
        {
            o.Stores.MaxLengthForKeys = 128;
            o.Password.RequireDigit = false;
            o.Password.RequireLowercase = false;
            o.Password.RequireUppercase = false;
            o.Password.RequireNonAlphanumeric = false;
            o.Password.RequiredLength = 6;
            o.Tokens.ProviderMap.Add("IAMEmailConfirmation", new TokenProviderDescriptor(typeof(CustomEmailConfirmationTokenProvider<AppUser>)));
            o.Tokens.EmailConfirmationTokenProvider = "IAMEmailConfirmation";
        });
        identityBuilder = new IdentityBuilder(identityBuilder.UserType, typeof(IdentityRole), identityBuilder.Services);
        identityBuilder.AddEntityFrameworkStores<AppIdentityDbContext>().AddDefaultTokenProviders();
    

    Is that what's causing the "warning as exception"? But why? It only happened after I upgraded the dotnet-ef tool to 10.0.1. This did NOT happen with 10.0.0: https://app.circleci.com/pipelines/github/khteh/AspNetCoreWebApi/639/workflows/7f3a7bc1-f0e7-4f06-96a1-52974e252f22/jobs/654

  19. roji commented on Dec 12, 2025

    @roji
    MemberAuthor

    @khteh please open a new issue with a minimal repro. Just posting a partial snippet is almost never enough.

  20. khteh commented on Dec 13, 2025

    @khteh

    I created migration and updated my DB successfully when 10.0.0 was released. Today, when I try to update the database using 10.0.1, it hits the same error as seen in the CI and my application is still running fine with the DB update previously applied using 10.0.0.

    https://github.com/khteh/AspNetCoreWebApi

  21. roji commented on Dec 13, 2025

    @roji
    MemberAuthor

    @khteh please follow the instructions I posted just above: posting a link to your full application does not constitute a minimal repro. Also, please open a new issue.

  22. khteh commented on Dec 13, 2025

    @khteh

    Didn't I open one and you closed it? #37352

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions