asp.net

NET8升级.NET9,Add-Migration xxx执行Update-DataBase报错

2024-12-27

在做netcore开发时,如果net8一直是正常的,只升级了一下框架net9,在使用Entity Framework Core的Code First模式进行迁移时,执行Add-Migration后尝试使用Update-DataBase时出现了如下错误。



Unhandled exception. System.InvalidOperationException: An error was generated for warning 'Microsoft.EntityFrameworkCore.Migrations.PendingModelChangesWarning': The model for context 'WasDbContext' 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.Migrate(String targetMigration)   at Npgsql.EntityFrameworkCore.PostgreSQL.Migrations.Internal.NpgsqlMigrator.Migrate(String targetMigration)   at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.Migrate(DatabaseFacade databaseFacade)   at Program.<Main>$(String[] args) in /Users/<REDACTED>/Program.cs:line 220

解决方法可参考,根据提示调整OnConfiguring'方法里的内容,调整如下


调整前

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder){optionsBuilder.UseSqlServer(“数据库链接字符串”);}


调整后

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder){base.OnConfiguring(optionsBuilder);optionsBuilder.ConfigureWarnings(warnings =>warnings.Log(RelationalEventId.PendingModelChangesWarning));optionsBuilder.UseSqlServer(“数据库链接字符串”);}


数据库中如果已经包含数据库了,第一次执行add-migration时,把Up和Down方法里的内容清空,执行update-database,执行前先确保model与数据库表结构完全一致。


protected override void Up(MigrationBuilder migrationBuilder) { }protected override void Down(MigrationBuilder migrationBuilder) { }

codefirst每次执行会验证上次执行结果,所以先跑一遍空方法,同步一下程序model和数据库结构。后面再开发需要调整表结构时,先修改model再接着add-migration upXXX 执行update-database。


如再遇到其他问题,根据Nuget 命令包net9与其它略有不同,根据提示情况再自行排查解决吧。