-
Notifications
You must be signed in to change notification settings - Fork 3.2k
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
Comments
/cc @AndriySvyryd |
@martincostello You are calling |
So has the code just been wrong forever, but it happened to just keep working anyway before 9.0-rc.1? |
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. |
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'. Code that fails Pease re-opened |
@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? |
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: |
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. |
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. |
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. |
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.EventDefinition
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.
This feels like a hack. |
@sbwalker Did you try creating a new migration? |
@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) 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. |
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 |
- FIX: PendingModelChangesWarning when creating new database dotnet/efcore#34431
Same issue since updating from .net 8 to .net 9 today. |
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? |
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. |
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. |
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)
public class Foo
}
|
@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. |
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
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? |
@pdevito3 here is at least one of the reasons that this error is happening now.
|
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 options.ConfigureWarnings(w => w.Ignore(RelationalEventId.PendingModelChangesWarning)) |
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 |
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. |
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. |
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'. |
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. 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. |
I updated my app to .NET9 and i get this error.
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. |
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. |
@AndriySvyryd thank you for posting this specific link to the documentation. By following the documentation I was able to resolve the problems. |
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? |
@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 |
resolved my issue thanks |
same problem when removing previous migration (while having pending changes of course) I used to have this error in previous version in specific cases but I'm not sure which. |
I have a "seeder" mechanism that loads data into migrations from // 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 // 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()); I have a seeder that uses
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 |
@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. |
I have same problem here 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 = "$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:
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
After:
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. |
Same problem on a console project we need for quick updates. We have no time to waste on this. |
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
using var scope = app.Services.CreateScope();
var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
if (context.Database.GetPendingMigrations().Any()) {
await context.Database.MigrateAsync();
} |
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
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.
The text was updated successfully, but these errors were encountered: