Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PendingModelChangesWarning when creating new database using .NET 9 rc.1 nightly build #34431

Closed
martincostello opened this issue Aug 14, 2024 · 95 comments

Comments

@martincostello
Copy link
Member

File a bug

I have a number of applications I am testing .NET 9 nightly builds with, and after updating them yesterday to start ingesting builds of .NET 9 rc.1 I have an application where tests are failing due to an InvalidOperationException being thrown after a new database is created.

No code changes have been made to the application, just updating to the latest .NET SDK and NuGet packages compared to the official .NET 9 preview 7 release.

The application under test creates a new database, deleting any existing database, and then performs a migration, but is now throwing an exception during migration starting that there are pending changes. There shouldn't be any pending migration as it is a newly created database.

Steps to reproduce

Clone martincostello/apple-fitness-workout-mapper@98b0602 and run build.ps1 from the root of the repository to build the application and run the tests.

Stack trace

 [2024-08-13 21:16:55Z] fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
       An unhandled exception has occurred while executing the request.
 System.InvalidOperationException: An error was generated for warning 'Microsoft.EntityFrameworkCore.Migrations.PendingModelChangesWarning': The model for context 'TracksContext' has pending changes. Add a new migration before updating the database. This exception can be suppressed or logged by passing event ID 'RelationalEventId.PendingModelChangesWarning' to the 'ConfigureWarnings' method in 'DbContext.OnConfiguring' or 'AddDbContext'.
    at Microsoft.EntityFrameworkCore.Diagnostics.EventDefinition`1.Log[TLoggerCategory](IDiagnosticsLogger`1 logger, TParam arg)
    at Microsoft.EntityFrameworkCore.Diagnostics.RelationalLoggerExtensions.PendingModelChangesWarning(IDiagnosticsLogger`1 diagnostics, Type contextType)
    at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.MigrateAsync(Func`4 seed, String targetMigration, Nullable`1 lockTimeout, CancellationToken cancellationToken)
    at MartinCostello.AppleFitnessWorkoutMapper.Services.TrackImporter.ImportTracksAsync(CancellationToken cancellationToken) in /_/src/AppleFitnessWorkoutMapper/Services/TrackImporter.cs:line 27
    at Program.<>c.<<<Main>$>b__0_12>d.MoveNext() in /_/src/AppleFitnessWorkoutMapper/Program.cs:line 201
 --- End of stack trace from previous location ---
    at Microsoft.AspNetCore.Http.Generated.<GeneratedRouteBuilderExtensions_g>F2A4F9050321DD26474371351A8857FE053630885E7CB9BFF3B12464F0B87EE32__GeneratedRouteBuilderExtensionsCore.<>c__DisplayClass6_0.<<MapPost3>g__RequestHandler|5>d.MoveNext() in /_/artifacts/obj/AppleFitnessWorkoutMapper/release/Microsoft.AspNetCore.Http.RequestDelegateGenerator/Microsoft.AspNetCore.Http.RequestDelegateGenerator.RequestDelegateGenerator/GeneratedRouteBuilderExtensions.g.cs:line 638
 --- End of stack trace from previous location ---
    at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)

Provider and version information

EF Core version: 9.0.0-rc.1.24402.2
Database provider: Microsoft.EntityFrameworkCore.Sqlite
Target framework: .NET 9.0
Operating system: GitHub Actions Linux, macOS and Windows runners
IDE: None.

@roji
Copy link
Member

roji commented Aug 14, 2024

/cc @AndriySvyryd

@AndriySvyryd
Copy link
Member

@martincostello You are calling context.Database.MigrateAsync, but there are no migrations in this project. That's what the warning is about.

@martincostello
Copy link
Member Author

So has the code just been wrong forever, but it happened to just keep working anyway before 9.0-rc.1?

@AndriySvyryd
Copy link
Member

It's not wrong, that call just doesn't do anything if there are no migrations. That's why we introduced the warning.

@los93sol
Copy link

It's not wrong, that call just doesn't do anything if there are no migrations. That's why we introduced the warning.

I'm having the same issue. Preview 7 works fine. Brand new DB, migrations apply just fine. Change nothing but upgrade to RC1 packages, start with a brand new DB and I get this warning and no migrations apply. The behavior is definitely different on RC1 packages and very unclear/unexpected with no indication as to what is actually different.

I also attempted to create a new migration on top of my existing migrations, but that just creates a new empty migration and the problem remains. I think this issue should be re-opened and investigated further.

@kmcdonald-EQIX
Copy link

I'm having the same issue. Preview 7 works finebut not RC1.

2024-09-20 09:38:49 System.InvalidOperationException: An error was generated for warning 'Microsoft.EntityFrameworkCore.Migrations.PendingModelChangesWarning': The model for context 'DbContext' has pending changes. Add a new migration before updating the database. This exception can be suppressed or logged by passing event ID 'RelationalEventId.PendingModelChangesWarning' to the 'ConfigureWarnings' method in 'DbContext.OnConfiguring' or 'AddDbContext'.
2024-09-20 09:38:49 at Microsoft.EntityFrameworkCore.Diagnostics.EventDefinition1.Log[TLoggerCategory](IDiagnosticsLogger1 logger, TParam arg)
2024-09-20 09:38:49 at Microsoft.EntityFrameworkCore.Diagnostics.RelationalLoggerExtensions.PendingModelChangesWarning(IDiagnosticsLogger`1 diagnostics, Type contextType)
2024-09-20 09:38:49 at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.MigrateAsync(String targetMigration, CancellationToken cancellationToken)
2024-09-20 09:38:49 at Npgsql.EntityFrameworkCore.PostgreSQL.Migrations.Internal.NpgsqlMigrator.MigrateAsync(String targetMigration, CancellationToken cancellationToken)
2024-09-20 09:38:49 at DbMigration.Services.MigrationService.ExecuteAsync(CancellationToken stoppingToken) in C:\Users\dev\source\repos\MyApp\DbMigration\Services\MigrationService.cs:line 44
2024-09-20 09:38:49 at Microsoft.Extensions.Hosting.Internal.Host.TryExecuteBackgroundServiceAsync(BackgroundService backgroundService)
2024-09-20 09:38:49 crit: Microsoft.Extensions.Hosting.Internal.Host[10]
2024-09-20 09:38:49 The HostOptions.BackgroundServiceExceptionBehavior is configured to StopHost. A BackgroundService has thrown an unhandled exception, and the IHost instance is stopping. To avoid this behavior, configure this to Ignore; however the BackgroundService will not be restarted.

Code that fails
using var dbContext = await _dbContextFactory.CreateDbContextAsync(stoppingToken);
var appliedMigrations = await dbContext.Database.GetAppliedMigrationsAsync(stoppingToken);
await dbContext.Database.MigrateAsync(stoppingToken);

Pease re-opened

@AndriySvyryd
Copy link
Member

I also attempted to create a new migration on top of my existing migrations, but that just creates a new empty migration and the problem remains. I think this issue should be re-opened and investigated further.

@los93sol That sounds like a bug. Can you open a new issue and share a small runnable repro project?

@kmcdonald-EQIX Did you try adding a new migration?

@los93sol
Copy link

los93sol commented Sep 20, 2024

Unfortunately repro is not so straightforward, I have been unable to repro outside of my real project so far so I don’t know exactly what the condition is that trips it, but sounds like at least 3 people have hit it already. I ignored the “warning” on rc1 packages and it did apply the migrations so something in that diff check seems like the culprit. I also would not expect a warning to abort like this, it results in a full on unhandled exception.

Another thing I tried was dropping existing migrations and just creating a brand new one against a new DB and it failed there as well so I don’t think it’s related to any previous migrations, but specifically something in that diff method that’s out of sync with the tooling to create migrations

@Ryba1986
Copy link

Unfortunately repro is not so straightforward, I have been unable to repro outside of my real project so far so I don’t know exactly what the condition is that trips it, but sounds like at least 3 people have hit it already. I ignored the “warning” on rc1 packages and it did apply the migrations so something in that diff check seems like the culprit. I also would not expect a warning to abort like this, it results in a full on unhandled exception.

Another thing I tried was dropping existing migrations and just creating a brand new one against a new DB and it failed there as well so I don’t think it’s related to any previous migrations, but specifically something in that diff method that’s out of sync with the tooling to create migrations

After setting the code below, the error stopped occurring:
`.UseNpgsql(.......)
.ConfigureWarnings(warnings => warnings.Log(RelationalEventId.PendingModelChangesWarning))``

@los93sol
Copy link

Same experience here, ignoring the warning makes it work correctly. The fact that ignoring the warning changes the behavior and multiple people have experienced it now points at a problem in that diff method.

@AndriySvyryd
Copy link
Member

Same experience here, ignoring the warning makes it work correctly. The fact that ignoring the warning changes the behavior and multiple people have experienced it now points at a problem in that diff method.

I'm not sure I follow. Ignoring the warning means that the exception shouldn't be thrown anymore, it doesn't change any other behavior.

To be able to investigate the underlying issue we need a repro project.

@yudielcurbelo
Copy link

I have the following code that runs in the Program.cs

using var scope = app.Services.CreateScope();
var context = scope.ServiceProvider.GetRequiredService<DbContextName>();
    
context.Database.Migrate();

I have one migration pending that has been created but not applied, and I'm getting the same exception. The migration is not being applied because of the exception.

Ignoring the exception will allow the project to apply the pending migration correctly.

options.ConfigureWarnings(warnings => { warnings.Log(RelationalEventId.PendingModelChangesWarning); });

This is not a permanent fix, but it applies the migration correctly.

@c5racing
Copy link

I can only reproduce this as the warning says. My model that is currently in code does not match the model that the migration is built off of.

@sbwalker
Copy link

sbwalker commented Oct 21, 2024

I have the same problem when migrating Oqtane (https://github.com/oqtane/oqtane.framework) to .NET 9

An Error Occurred Provisioning The Master Database. This Is Usually Related To The Master Database Not Being In A Supported State. System.InvalidOperationException: An error was generated for warning 'Microsoft.EntityFrameworkCore.Migrations.PendingModelChangesWarning': The model for context 'MasterDBContext' has pending changes. Add a new migration before updating the database. This exception can be suppressed or logged by passing event ID 'RelationalEventId.PendingModelChangesWarning' to the 'ConfigureWarnings' method in 'DbContext.OnConfiguring' or 'AddDbContext'. at Microsoft.EntityFrameworkCore.Diagnostics.EventDefinition1.Log[TLoggerCategory](IDiagnosticsLogger1 logger, TParam arg) at Microsoft.EntityFrameworkCore.Diagnostics.RelationalLoggerExtensions.PendingModelChangesWarning(IDiagnosticsLogger`1 diagnostics, Type contextType) at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration) at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.Migrate(DatabaseFacade databaseFacade) at Oqtane.Infrastructure.DatabaseManager.MigrateMaster(InstallConfig install) in C:\Source\Projects\oqtane.framework\Oqtane.Server\Infrastructure\DatabaseManager.cs:line 271

using (var masterDbContext = new MasterDBContext(new DbContextOptions<MasterDBContext>(), null, _config))
{
    AddEFMigrationsHistory(sql, install.ConnectionString, install.DatabaseType, "", true);
    // push latest model into database
    masterDbContext.Database.Migrate();
    result.Success = true;
}

This logic has worked in every .NET Core release from 3.1 to 8.0 - however it is throwing an exception in .NET 9.

Suppressing the exception resolved the issue and allowed the migrations to be executed successfully.

            database.UseDatabase(optionsBuilder, connectionString)
                .ConfigureWarnings(warnings => warnings.Log(RelationalEventId.PendingModelChangesWarning));

This feels like a hack.

@AndriySvyryd
Copy link
Member

@sbwalker Did you try creating a new migration?

@sbwalker
Copy link

@AndriySvyryd all of the migration classes are included in the application (https://github.com/oqtane/oqtane.framework/tree/dev/Oqtane.Server/Migrations/Master) providing a seamless installation and upgrade experience (for SQL Server, SQLite, MySQL, PostgreSQL)

Image

It is not clear what you mean by "creating a new migration"? The existing migration classes were created manually without using any command line tools, etc... This is necessary because Oqtane is multi-tenant and requires specific conventions for DbContext to determine how a tenant maps to a specific database. I would certainly hope that I would not need to recreate any Migration classes... if that were true, it would mean that there was a major breaking change in EF Core.

@AndriySvyryd
Copy link
Member

The existing migration classes were created manually without using any command line tools, etc...

I see. Then indeed this is a false positive, the warning is only intended for applications using ef tools to create the migrations. You can safely .Ignore it

@wstaelens
Copy link

Same issue since updating from .net 8 to .net 9 today.

@sebastianbk
Copy link

Our team is experiencing the same issue. We followed the migration guide and still ran into this issue. There are no changes/migrations pending.

Is this a bug or how do we get around this issue?

@AndriySvyryd
Copy link
Member

In my case I have pre-existing migrations that generate values dynamically so I guess that’s the issue as others pointed out, but that was previously supported so this change is breaking things that cannot be changed in existing projects which makes it especially bad.

I see. That's still supported, just strongly discouraged as it could result in unnecessary changes each time you add a new migration. That's why you need to explicitly opt-in by ignoring the warning.

@bcanylmz
Copy link

bcanylmz commented Dec 4, 2024

I am using MSSQL, I solved my problem by removing the HasData method. It is a suggestion for friends who get the error. The problem is either in the Guid.NewGuid() method or in the HasData method. After doing this, I was able to get migration.

@wstaelens
Copy link

updated another project from .net 8 to .net 9 (sql server express) and suddenly I have this pending-migration and the same issue.

    ```

protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DeleteData(
table: "AspNetRoles",
keyColumn: "Id",
keyValue: "");

        migrationBuilder.AlterColumn<string>(
            name: "Discriminator",
            table: "AspNetRoles",
            type: "nvarchar(21)",
            maxLength: 21,
            nullable: false,
            oldClrType: typeof(string),
            oldType: "nvarchar(max)");

        migrationBuilder.InsertData(
            table: "AspNetRoles",
            columns: new[] { "Id", "ConcurrencyStamp", "Discriminator", "Name", "NormalizedName" },
            values: new object[] { "<guid>", null, "ApplicationRole", "Administartor", "ADMINISTARTOR" });
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
// ...

I have some tables where I create some unique guids:

public class Foo
{
[Key]
public int Id { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid UniqueId { get; set; }
}

  protected override void OnModelCreating(ModelBuilder builder)
  {
      base.OnModelCreating(builder);
      // ...
        builder.Entity<Foo>().Property(x => x.UniqueId).HasDefaultValueSql("newid()");

// ...

}



resolved it for now by doing:

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        base.OnConfiguring(optionsBuilder);
        optionsBuilder.ConfigureWarnings(warnings => warnings.Log(RelationalEventId.PendingModelChangesWarning));

    }

@pcoganwu
Copy link

pcoganwu commented Dec 4, 2024

@bcanylmz, the problem is not the HasData(). Initializing Properties with default values like Guid.NewGuid() or DateTime.Now causes the issue you are seeing. Properties have to be initialize with values like Id = Guid.Parse("5D39AFF6-78B2-1B5A-05B1-D2202F0BC633"). Not sure if this is a bug or it was designed to throw the exception we are seeing.

@pdevito3
Copy link

pdevito3 commented Dec 5, 2024

Yeah, this totally breaks my integration tests and doesn't even make sense to me. y'all are saying that the migrations aren't present and added the error because this code isn't doing anything but removing the migrations that you say do nothing literally causes and error because my migrations don't run. they clearly do as they have for several .net versions now

here are the lines

[CollectionDefinition(nameof(TestFixture))]
public class TestFixtureCollection : ICollectionFixture<TestFixture> {}

public class TestFixture : IAsyncLifetime
{
    public static IServiceScopeFactory BaseScopeFactory;
    private PostgreSqlContainer _dbContainer;
    private RabbitMqContainer _rmqContainer;
    private LocalStackContainer _localStackContainer;

    public async Task InitializeAsync()
    {
        var builder = WebApplication.CreateBuilder(new WebApplicationOptions
        {
            EnvironmentName = Consts.Testing.IntegrationTestingEnvName
        });

        _dbContainer = new PostgreSqlBuilder().Build();
        await _dbContainer.StartAsync();
        builder.Configuration.GetSection(ConnectionStringOptions.SectionName)[ConnectionStringOptions.PeakLimsKey] = _dbContainer.GetConnectionString();
        await RunMigration(_dbContainer.GetConnectionString());

        // other
    }
    
    private static async Task RunMigration(string connectionString)
    {
        var options = new DbContextOptionsBuilder<PeakLimsDbContext>()
            .UseNpgsql(connectionString)
            .Options;
        var context = new PeakLimsDbContext(options, null, null, null);
        await context?.Database?.MigrateAsync();
    }
}

if you want repro, just clone this down:

this completely breaks projects in .net 9 upgrades for no good reason y'all. even if the code is 'doing nothing' like you think, why totally block us with an error vs a warning?

@michaelakin
Copy link

michaelakin commented Dec 5, 2024

@pdevito3 here is at least one of the reasons that this error is happening now.

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

@AndriySvyryd
Copy link
Member

this completely breaks projects in .net 9 upgrades for no good reason y'all. even if the code is 'doing nothing' like you think, why totally block us with an error vs a warning?

We understand that this can be frustrating, but unfortunately we know that many developers don't see the warnings if they are just logged.

If you are ok with the Migrate call being no-op then ignore the warning:

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

@pdevito3
Copy link

pdevito3 commented Dec 5, 2024

If you are ok with the Migrate call being no-op then ignore the warning:

I understand this an option but requires an explicit code update to prevent a break which sucks. Also, it is absolutely not a no-op for me. My migration only works with this setup, even if this error says it does nothing

@roji
Copy link
Member

roji commented Dec 6, 2024

Note: we've just published #35285 which provides more background and explanations around the new PendingModelChangesWarning; anyone still having trouble should go read that - hopefully it should help.

@leshaaa
Copy link

leshaaa commented Dec 7, 2024

This exception can also be caused by using Unicode characters in HasData calls in source files saved in ANSI encoding.

TL;DR

Hey everyone, let me add one more case for when this error occurs. Yesterday, I also encountered the PendingModelChangesWarning issue. It happened right after I recently upgraded to .NET 9.0. I added several lines with HasData to the model configuration, then created a migration and successfully tested it locally. However, when I deployed it to the remote server, the application started crashing with the PendingModelChangesWarning exception when attempting to run the Migrate() method. I spent several hours unsuccessfully investigating this, exploring this thread and the EF Core documentation. I was about to suppress the warning via ConfigureWarnings, but at the last moment, I accidentally realized that the issue was with the file encoding. The file in which I was calling HasData was encoded in ANSI and contained some non-standard characters. When running migrations on my local Windows machine, everything worked fine, but on the remote server running Ubuntu, these non-standard characters were corrupted. The issue was easily fixed by converting the source code file from ANSI to Unicode encoding.

In fact, I think it’s great that this check was added in EF 9.0. It's a safeguard against unexpected errors. However, I think it would be much easier for developers to resolve issues if the exception message didn't just say "The model for context 'DbContext' has pending changes," but instead provided more detailed information about how to see these changes. If I could see that difference, I would have spent 5 minutes fixing the issue instead of 5 hours.

@jrlopez83
Copy link

I have the same issue after adding 1 table to the model, I did generate a new migration and it did not work, after several other tries, I ended deleting the existing DB in the Server, deleting all the files under the migrations folder and all the files under the obj folder (i don't know why I did this last one), generating a new Initial Migration... And still it continues to show the same. I cleared the cache, restarted the computer, cleaned the temp folder, cleaned the migrations once again, and nothing works. It still throws:

"System.InvalidOperationException: An error was generated for warning 'Microsoft.EntityFrameworkCore.Migrations.PendingModelChangesWarning': The model for context 'MyProjectDB' has pending changes. Add a new migration before updating the database. This exception can be suppressed or logged by passing event ID 'RelationalEventId.PendingModelChangesWarning' to the 'ConfigureWarnings' method in 'DbContext.OnConfiguring' or 'AddDbContext'.
at Microsoft.EntityFrameworkCore.Diagnostics.EventDefinition1.Log[TLoggerCategory](IDiagnosticsLogger1 logger, TParam arg)
at Microsoft.EntityFrameworkCore.Diagnostics.RelationalLoggerExtensions.PendingModelChangesWarning(IDiagnosticsLogger`1 diagnostics, Type contextType)
at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
at Npgsql.EntityFrameworkCore.PostgreSQL.Migrations.Internal.NpgsqlMigrator.Migrate(String targetMigration)
at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String connectionString, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabaseImpl(String targetMigration, String connectionString, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_0.<.ctor>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
An error was generated for warning 'Microsoft.EntityFrameworkCore.Migrations.PendingModelChangesWarning': The model for context 'MyProjectDB' has pending changes. Add a new migration before updating the database. This exception can be suppressed or logged by passing event ID 'RelationalEventId.PendingModelChangesWarning' to the 'ConfigureWarnings' method in 'DbContext.OnConfiguring' or 'AddDbContext'."

@Kyeong-min
Copy link

I got the same error in EF Core 9.

In my case, this error occurred after removing the [Required] attribute from a string property that had the [Required, MaxLength(100)] attribute declared.

Specifically, after applying a particular migration to the DB, I realized that I had made a mistake and removed the Required attribute.
We then attempted to update to a previous version and encountered the issue.

After reinserting the required attribute, I was able to update, and once again, deleting the required attribute allowed me to add the migration and update.

@FritzTheCat9
Copy link

I updated my app to .NET9 and i get this error.

Image

[20:26:50 ERR ] [DatabaseInitializer] Error while creating and migrating the database: "An error was generated for warning 'Microsoft.EntityFrameworkCore.Migrations.PendingModelChangesWarning': The model for context 'AppDbContext' has pending changes. Add a new migration before updating the database. This exception can be suppressed or logged by passing event ID 'RelationalEventId.PendingModelChangesWarning' to the 'ConfigureWarnings' method in 'DbContext.OnConfiguring' or 'AddDbContext'."

I removed all previous migrations. And created one new migration. It did not helped.

So i removed this lines in my DbContext class. Then removed all migrations and created one. It helped. But dont know why from now we can not have dynamic migration setup (like dates in my example). I think it should work and be fixed ASAP.

Image

#35285

@AndriySvyryd
Copy link
Member

But dont know why from now we can not have dynamic migration setup (like dates in my example). I think it should work and be fixed ASAP.

We always discouraged this in the documentation. With this in your model each time a migration was added it included commands to update all those dynamic dates to the date that the migration was created. If you do want this behavior, you can ignore the warning as described above.

@Sineshaper
Copy link

@AndriySvyryd thank you for posting this specific link to the documentation. By following the documentation I was able to resolve the problems.

@FritzTheCat9
Copy link

@AndriySvyryd

"If you do want this behavior, you can ignore the warning as described above."

I can not just ignore this error. Migrations are not applying on my application start. So database will not be created and migrated. So i think it is a breaking change. I had to update my code that used to work on .NET 8.

@AndriySvyryd
Copy link
Member

I can not just ignore this error. Migrations are not applying on my application start. So database will not be created and migrated. So i think it is a breaking change. I had to update my code that used to work on .NET 8.

So, are you still getting errors after adding this line to options?

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

Can you create a small repro project?

@FritzTheCat9
Copy link

@AndriySvyryd I did not add this code. I resolved my bug by removing dynamic data from migrations. For now its ok. Thank You for help <3

@jonyustc
Copy link

I can not just ignore this error. Migrations are not applying on my application start. So database will not be created and migrated. So i think it is a breaking change. I had to update my code that used to work on .NET 8.

So, are you still getting errors after adding this line to options?

options.ConfigureWarnings(w => w.Ignore(RelationalEventId.PendingModelChangesWarning))
Can you create a small repro project?

resolved my issue thanks

@sebestyn168
Copy link

sebestyn168 commented Dec 17, 2024

same problem when removing previous migration (while having pending changes of course)
update-database -project $DalProject -StartupProject $WebProject -context $DbContext -v $PreviousMigration

I used to have this error in previous version in specific cases but I'm not sure which.
So Ignoring PendingChanges in configuration solves the problem but I feel like a safety net has been removed.

@keyzzrivas
Copy link

keyzzrivas commented Dec 26, 2024

I can not just ignore this error. Migrations are not applying on my application start. So database will not be created and migrated. So i think it is a breaking change. I had to update my code that used to work on .NET 8.

So, are you still getting errors after adding this line to options?

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

Can you create a small repro project?

I have a "seeder" mechanism that loads data into migrations from .json files or from collections.
By removing this feature, the InsertData was no longer generated and that made everything work.

// 20241226064941_Initial.cs
migrationBuilder.InsertData(
    table: "members",
    columns: new[] { "id", "email", "username", "failed_access_attempts", etc... },
    values: new object[] { new Guid("..."), "[email protected]", "admin", null, etc... });

But, I needed my data, so thanks @AndriySvyryd
This worked for me 🎉

// Define DB Context in Program.cs
builder.Services.AddDbContext<DataContext>((serviceProvider, options) =>
    options
    .UseNpgsql(dataSource)
    .AddInterceptors(serviceProvider.GetRequiredService<SoftDeleteInterceptor>())
    .UseSnakeCaseNamingConvention()
    .ConfigureWarnings(w => w.Ignore(RelationalEventId.PendingModelChangesWarning)) // <--- This line ✨
    .EnableDetailedErrors());

⚠️ UPDATE:

I have a seeder that uses Guid.NewGuid() and DateTime.UtcNow and according to this article "it's built in a non-deterministic way":
https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-9.0/breaking-changes

The model wasn't modified by the developer, but it's built in a non-deterministic way causing EF to detect it as modified. This is common when new DateTime(), DateTime.Now, DateTime.UtcNow, or Guid.NewGuid() are used in objects supplied to HasData().

public class MembersSeeder : ISeeder
{
    public void Run(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Member>().HasData(new Member()
        {
            Id = Guid.NewGuid(),
            // ...
            CreatedAt = DateTime.UtcNow,
            UpdatedAt = DateTime.UtcNow,
        });
    }
}

By removing this Seeder everything works correctly and it is no longer necessary to suppress the warnings Ignore(RelationalEventId.PendingModelChangesWarning).

@roji
Copy link
Member

roji commented Dec 27, 2024

@keyzzrivas great that everything is working for you. But as explained in #35285, you don't need to remove your data - simply replcae Guid.NewGuid() and DateTime.UtcNow with specific values.

@a7son
Copy link

a7son commented Dec 30, 2024

I have same problem here
I seed the data like this, and it keep throwing an error
var adminUser = new User
{
Id = 1,
Name = "admin",
Email = "[email protected]",
Phone = "1234567890",
Role = nameof(UserRole.Admin),
IsApproved = true
};

adminUser.PasswordHash = _passwordHasher.HashPassword(adminUser, "123456");

modelBuilder.Entity().HasData(adminUser);

I remove this line and it works. but my data doesn't seed

@roji
Copy link
Member

roji commented Dec 30, 2024

@a7son we have no idea what your HashPassword function does; try running it once and integrating the string result of that in the seed data (this is all explained in #35285).

@keyzzrivas
Copy link

I have same problem here I seed the data like this, and it keep throwing an error var adminUser = new User { Id = 1, Name = "admin", Email = "[email protected]", Phone = "1234567890", Role = nameof(UserRole.Admin), IsApproved = true };

adminUser.PasswordHash = _passwordHasher.HashPassword(adminUser, "123456");

modelBuilder.Entity().HasData(adminUser);

I remove this line and it works. but my data doesn't seed

@a7son I had the same problem with passwords in seeders, I'm using the package Isopoh.Cryptography.Argon2, every time you generate a password the Hash is different even if the password is the same "123456", that causes the warning.

The solution is to generate a hash and place the static string in the adminUser.PasswordHash property:

adminUser.PasswordHash = "$argon2id$v=19$m=65536,t=3,p=1$QWTjH2VsGH ..."
modelBuilder.Entity().HasData(adminUser);

@irvanherz
Copy link

I have same problem here I seed the data like this, and it keep throwing an error var adminUser = new User { Id = 1, Name = "admin", Email = "[email protected]", Phone = "1234567890", Role = nameof(UserRole.Admin), IsApproved = true };
adminUser.PasswordHash = _passwordHasher.HashPassword(adminUser, "123456");
modelBuilder.Entity().HasData(adminUser);
I remove this line and it works. but my data doesn't seed

@a7son I had the same problem with passwords in seeders, I'm using the package Isopoh.Cryptography.Argon2, every time you generate a password the Hash is different even if the password is the same "123456", that causes the warning.

The solution is to generate a hash and place the static string in the adminUser.PasswordHash property:

adminUser.PasswordHash = "$argon2id$v=19$m=65536,t=3,p=1$QWTjH2VsGH ..."
modelBuilder.Entity().HasData(adminUser);

I encountered same issue. After the upgrade, every time I executed dotnet ef database update, I received the following error:

An error was generated for warning 'Microsoft.EntityFrameworkCore.Migrations.PendingModelChangesWarning': The model for context 'AppDbContext' has pending changes. Add a new migration before updating the database. This exception can be suppressed or logged by passing event ID 'RelationalEventId.PendingModelChangesWarning' to the 'ConfigureWarnings' method in 'DbContext.OnConfiguring' or 'AddDbContext'.

I was able to resolve it by switching from dynamically generating the password hash during seeding to using a precomputed static hash. Here's what I did:

Before

builder.Entity<User>()
    .HasData(new User 
    { 
        Id = 1, 
        Username = "root", 
        Email = "[email protected]", 
        FullName = "Root", 
        Password = BCrypt.Net.BCrypt.HashPassword("root", 6), 
        Role = UserRole.Super, 
        Gender = UserGender.Other 
    });

After:

builder.Entity<User>()
    .HasData(new User 
    { 
        Id = 1, 
        Username = "root", 
        Email = "[email protected]", 
        FullName = "Root", 
        Password = "$2y$08$418wcq/JSnXBzU3yN/Xpje7tnqxEP8uGx7R9r3YMzLc1AF71a.Tj6", 
        Role = UserRole.Super, 
        Gender = UserGender.Other, 
        CreatedAt = Instant.FromUnixTimeTicks(17366053651766652L), 
        UpdatedAt = Instant.FromUnixTimeTicks(17366053651766652L) 
    });

In addition to using a precomputed password hash ("$2y$08$418wcq/..."), I also had to generate fixed values for CreatedAt and UpdatedAt. These fields kept changing with its default value (now) each run and were likely causing the PendingModelChangesWarning as well.

@sebestyn168
Copy link

Same problem on a console project we need for quick updates. We have no time to waste on this.
In my opinion this evolution should have only impact new Migrations marked with an Attribute.

@vimerzzz
Copy link

So after i read the docs on this https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-9.0/breaking-changes#mitigations, seems like we can't use dynamic data like Guid.NewGuid(), DateTime.Now in HasData(). Then i tried some solutions and this worked for me, which still had dynamic data for seeding, no need to add ConfigureWarning

  1. UseSeeding and UseAsyncSeeding after UseNpgsql/UseSqlServer, just move all data for seeding to these blocks. Read more on this docs https://learn.microsoft.com/en-us/ef/core/modeling/data-seeding#use-seeding-method.
  2. If you have some migrations before, just double Add-Migration in Package Manager Console, first is used to remove the old data, second is just make sure that there's nothing in Up() and Down() method.
  3. With this code, the UseAsyncSeeding will run every time you have a new migration.
using var scope = app.Services.CreateScope();
var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
if (context.Database.GetPendingMigrations().Any()) {
    await context.Database.MigrateAsync();
}

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

No branches or pull requests