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 · 54 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?

@michaelakin
Copy link

michaelakin commented Nov 21, 2024

@pcoganwu @PureIso We cannot help you until you open a new issue and provide a small runnable repro project

I just tried this and I am having the same issue. Seems silly to have to add the suppression to this. Interestingly, I am also running postgres.

@los93sol
Copy link

@pcoganwu @PureIso We cannot help you until you open a new issue and provide a small runnable repro project

This issue should have never been closed. I don’t mean to be negative, but a lot of us are helping vet these things early and in most cases when we point things like this out early we are ignored. I’m super disappointed with how this is being handled.

@wstaelens
Copy link

While I’m unable to provide a repro at this time, I suspect the issue might be related to PostgreSQL, Npgsql, and DateTime.

Interestingly, the HasDifferences method returns true, yet no changes are generated in the migration.

Fortunately, there’s also a public method called GetDifferences, which, in our case, returns 48 items. Each item corresponds to an AlterTableOperation for one of our DateTime properties.

Does this sound familiar to anyone else?

I have SQL Server and the same issue, so don't think it is only related to PostgreSQL, Npgsql

@roji
Copy link
Member

roji commented Nov 22, 2024

@los93sol and others, we're not doubting that there's an issue somewhere - either in user code, or possibly a bug in EF itself. However, we simply cannot investigate further and help out with a repro: the above contains "I have this too" comments and general text about the problem, but we're lacking a simple, clear code sample that we can look at and investigate.

The fact that this issue is currently closed only means exactly that - it's not currently actionable for us, since given the lack of a repro we can't investigate. That doesn't mean that we're not here to help, and if someone does the work of putting together a repro, the issue can be reopened (or in this case, it may be better to open a new one). So I don't think there should be any reason to be disappointed - we're here to help regardless of whether this issue is currently in the closed or open state.

@PureIso
Copy link

PureIso commented Nov 22, 2024

@los93sol and others, we're not doubting that there's an issue somewhere - either in user code, or possibly a bug in EF itself. However, we simply cannot investigate further and help out with a repro: the above contains "I have this too" comments and general text about the problem, but we're lacking a simple, clear code sample that we can look at and investigate.

The fact that this issue is currently closed only means exactly that - it's not currently actionable for us, since given the lack of a repro we can't investigate. That doesn't mean that we're not here to help, and if someone does the work of putting together a repro, the issue can be reopened (or in this case, it may be better to open a new one). So I don't think there should be any reason to be disappointed - we're here to help regardless of whether this issue is currently in the closed or open state.

Apologies, was simply trying to help other developers with a wor around:
Here is a repo:
https://github.com/PureIso/DomainDrivenWebApplication
To be more specific: https://github.com/PureIso/DomainDrivenWebApplication/blob/main/src/DomainDrivenWebApplication.Infrastructure/Data/SchoolContext.cs - recreate by removing the ConfigureWarnings. Can run the docker-compose

@ajcvickers
Copy link
Member

Thanks @PureIso for the repro. I filed #35181 to track this specific case, since there is a lot of noise on this issue already.

I suspect there may other different causes that can also result in the same exception, so, everyone, if you have another repro you can share, then please do!

@karwanessmat
Copy link

I got
"
An error was generated for warning 'Microsoft.EntityFrameworkCore.Migrations.PendingModelChangesWarning': The model for context 'SpardaDbContext' 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'.

while the .net 9 is running on LTS.

@sbwalker
Copy link

@ajcvickers I added another repro to #35181 - or were you wanting a separate issue to be created for each repro?

@michaelakin
Copy link

michaelakin commented Nov 22, 2024

@los93sol @ajcvickers I think it has to do with this line in School.cs

public DateTime CreatedAt { get; set; } = DateTime.UtcNow;

I updated some configs to use a constant date for the seeding of some lookup tables and the problem has went away.

public static DateTime CreateDateTime = new DateTime(new DateOnly(2024, 11, 1), new TimeOnly(0, 0, 0), DateTimeKind.Utc);

I noticed even before that because of this UTC date, that it would put seeding in every migration whether it needed it or not because the date and time was different. That is at least one reason that it alwasy thinks that there is a migration needed to be applied. Not matter what you do, there will always be another migration needed because the DateTime values have changed.

Apologies, was simply trying to help other developers with a wor around: Here is a repo: https://github.com/PureIso/DomainDrivenWebApplication To be more specific: https://github.com/PureIso/DomainDrivenWebApplication/blob/main/src/DomainDrivenWebApplication.Infrastructure/Data/SchoolContext.cs - recreate by removing the ConfigureWarnings. Can run the docker-compose

@pcoganwu
Copy link

I added a new repo with the issue. There is a pending migration to be added to the database with update-database command. The issue occurs when the update-database command is ran. Below is the url to the repo

https://github.com/pcoganwu/EFCore_Issue

@michaelakin
Copy link

I added a new repo with the issue. There is a pending migration to be added to the database with update-database command. The issue occurs when the update-database command is ran. Below is the url to the repo

https://github.com/pcoganwu/EFCore_Issue

Remove the DateTime.UtcNow in the data seeding. that will fix it.

@pcoganwu
Copy link

I have DateTime.UtcNow in my code. Will edit to see if this fixes the issue.

@pcoganwu
Copy link

I am still getting the exception after update the DateTime.UtcNow as per Micael's suggestion. I have updated the repo with the changes.

                      System.InvalidOperationException: An error was generated for warning 'Microsoft.EntityFrameworkCore.Migrations.PendingModelChangesWarning': The model for context 'ApplicationDbContext' 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 'ApplicationDbContext' 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'.

Below is my ApplicationDbContext class with the seed data

@michaelakin
Copy link

I am still getting the exception after update the DateTime.UtcNow as per Micael's suggestion. I have updated the repo with the changes.

Try removing this:

Image

This may work, but seems like an unfortunate bug.

@pcoganwu
Copy link

Thanks Michael. I will try it and revert.

@pcoganwu
Copy link

@michaelakin I updated the code as suggested, the issue is still there. I have updated the repo.

@AndriySvyryd
Copy link
Member

@michaelakin I updated the code as suggested, the issue is still there. I have updated the repo.

You are using Id = Guid.NewGuid() in object supplied to HasData, that has the same issue

@pcoganwu
Copy link

@AndriySvyryd Changing the Id = Guid.NewGuid() to Id = Guid.Parse("6875C4A1-7668-BC3E-7FA3-F711CD6C5962") fixed the issue. This is weird anyway. I have updated the repo with a working code.

@mahmutozerg
Copy link

mahmutozerg commented Nov 23, 2024

Beside the workaround, the only way to use IdendityDb is i've migrated from 8.0 and all my seed data are thrash. I can't even use this version due to password hash. Any dynamic data causes this error
Image

@stevenrlp
Copy link

I am still seeing this issue with the .net 9 release, am I correct in assuming that this is the intended behaviour to throw an exception when calling context.Database.MigrateAsync when there are no pending changes? or is this a bug that is going to be fixed in a future version? I can see many users are going to be experiencing this issue when they migrate to .net 9.

@mahmutozerg
Copy link

mahmutozerg commented Nov 25, 2024

Disclaimer I am not a certified ".Net Pro" but the the Current solution that ı've found is creating seed data at run time not at migration. You can see the full solution at . I hope this solution helps to all

https://github.com/mahmutozerg/DotNetNlayer/blob/main/DotNetNlayer/DotNetNlayer.API/Seeders/UserRoleSeeder.cs
or sample code

namespace DotNetNlayer.API.Seeders;

public static class UserRoleSeeder
{
public static async Task SeedRolesToUser(IServiceProvider serviceProvider)
{
await using var scope = serviceProvider.CreateAsyncScope();

    var services = scope.ServiceProvider;
    
    try
    {
        var roleManager = services.GetRequiredService<RoleManager<AppRole>>();
        var userManager = services.GetRequiredService<UserManager<AppUser>>();
        
        foreach (var role in RoleConstants.Roles)
        {
            if (!await roleManager.RoleExistsAsync(role))
            {
                await roleManager.CreateAsync(new AppRole(role));
            }
        }

        const string adminEmail = SeedConstants.AdminEmail;
        var adminUser = await userManager.FindByEmailAsync(adminEmail);

        if (adminUser == null)
        {
            adminUser = new AppUser
            {
                UserName = SeedConstants.AdminUserName,
                Email = adminEmail,
                EmailConfirmed = true, // Consider email confirmed for seeding
                CreatedBy = "SeedData",
                UpdatedBy = "SeedData",
                CreatedAt = DateTime.Now,
                UpdatedAt = DateTime.Now
            };

            var result = await userManager.CreateAsync(adminUser, SeedConstants.AdminPassword);

            if (result.Succeeded)
            {
                var userCreateResult = await userManager.AddToRoleAsync(adminUser, "Admin");
                if(!userCreateResult.Succeeded)
                    throw new SomethingWentWrongException(nameof(AppUser),string.Join(Environment.NewLine, userCreateResult.Errors.Select(e => e.Description)));
            }
        
        }
    }
    catch (Exception ex)
    {
        throw new SomethingWentWrongException(nameof(AppRole), "Something went wrong while role seeding");
    }
}

}

@michaelakin
Copy link

I am still seeing this issue with the .net 9 release, am I correct in assuming that this is the intended behavior to throw an exception when calling context.Database.MigrateAsync when there are no pending changes? or is this a bug that is going to be fixed in a future version? I can see many users are going to be experiencing this issue when they migrate to .net 9.

I am not sure if Microsoft will fix it, but the problem seems to be with default dates or new GUIDS (or anything that will be different every time) in seed data or or in the models or seed data. This will cause it to think there is a new migration needed.

@sbwalker
Copy link

If this issue is not fixed then it should at least be identified as a "breaking behavioral change" for .NET 9, as it breaks a lot of existing applications which worked fine on all prior .NET Core releases.

@stevenrlp
Copy link

I am still seeing this issue with the .net 9 release, am I correct in assuming that this is the intended behavior to throw an exception when calling context.Database.MigrateAsync when there are no pending changes? or is this a bug that is going to be fixed in a future version? I can see many users are going to be experiencing this issue when they migrate to .net 9.

I am not sure if Microsoft will fix it, but the problem seems to be with default dates or new GUIDS (or anything that will be different every time) in seed data or or in the models or seed data. This will cause it to think there is a new migration needed.

I don't think that is correct, my seed data does not contain any dates or GUIDs, it just has static string, numeric and boolean values, and I am still getting the exception. I was able to bypass it by using options.ConfigureWarnings(warnings => { warnings.Log(RelationalEventId.PendingModelChangesWarning); }); but I don't think people should have to go and update all their projects. It isn't a bit change but it just feels wrong and dirty to have to cover up an error like that. And why does a "warning" cause an "exception", that doesn't make sense. I really hope the team addresses this issue.

@AndriySvyryd
Copy link
Member

AndriySvyryd commented Nov 25, 2024

Disclaimer I am not a certified ".Net Pro" but the the Current solution that ı've found is creating seed data at run time not at migration. You can see the full solution at . I hope this solution helps to all

@mahmutozerg Yes, for Identity it's recommended to seed at runtime and not use HasData

I am not sure if Microsoft will fix it, but the problem seems to be with default dates or new GUIDS (or anything that will be different every time) in seed data or in the models or seed data. This will cause it to think there is a new migration needed.

@michaelakin That's a limitation of HasData and cannot be fixed on the EF side.

If this issue is not fixed then it should at least be identified as a "breaking behavioral change" for .NET 9, as it breaks a lot of existing applications which worked fine on all prior .NET Core releases.

@sbwalker Yes, we'll do it soon but note that this week is shorter due to holidays in the US.

@stevenrlp Do you get an empty migration if you create a new one? If so, please file a new issue and share a small repro project.


For everyone who wants to use seeding with non-deterministic values we've added a better way of doing so in 9.0

@bcanylmz
Copy link

bcanylmz commented Nov 29, 2024

All Migration and Database Table Remove then
I switched from .net 8 to .net and it's really frustrating. I can't develop my project right now, it's like a joke.
Isn't 9.0 the stable version?

An error occurred while migrating the database.
System.InvalidOperationException: 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'.

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