You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

EF Core 7添加HasColumnName时触发NullReferenceException异常

问题描述

使用EF Core 7.0.7搭配.NET 8,修改实体属性的列名配置后,执行数据库迁移时报空引用异常。

旧实体配置

builder.Property(c => c.AddressId).IsRequired();

新实体配置

builder.Property(c => c.AddressId).IsRequired().HasColumnName("addressId");

执行的迁移命令

dotnet ef migrations add UpdateFieldName
dotnet ef database update

报错信息

System.NullReferenceException: 对象引用未设置为对象的实例。

at MySql.EntityFrameworkCore.Migrations.MySQLMigrationsSqlGenerator.Generate(RenameColumnOperation operation, IModel model, MigrationCommandListBuilder builder)
at Microsoft.EntityFrameworkCore.Migrations.MigrationsSqlGenerator.<>c.<.cctor>b__82_22(MigrationsSqlGenerator g, MigrationOperation o, IModel m, MigrationCommandListBuilder b)
at Microsoft.EntityFrameworkCore.Migrations.MigrationsSqlGenerator.Generate(MigrationOperation operation, IModel model, MigrationCommandListBuilder builder)
at MySql.EntityFrameworkCore.Migrations.MySQLMigrationsSqlGenerator.Generate(MigrationOperation operation, IModel model, MigrationCommandListBuilder builder)
at Microsoft.EntityFrameworkCore.Migrations.MigrationsSqlGenerator.Generate(IReadOnlyList`1 operations, IModel model, MigrationsSqlGenerationOptions options)
at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.GenerateUpSql(Migration migration, MigrationsSqlGenerationOptions options)
at MySql.EntityFrameworkCore.Migrations.Internal.MySQLMigrator.GenerateUpSql(Migration migration, MigrationsSqlGenerationOptions options)
at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.<>c__DisplayClass16_2.b__2()
at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.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)

对象引用未设置为对象的实例。

解决方法

这个异常是MySQL EF Core提供程序与EF Core、.NET版本不兼容导致的,可按以下步骤解决:

  • 统一EF Core版本:将所有EF Core相关NuGet包(包括Microsoft.EntityFrameworkCore、MySql.EntityFrameworkCore等)升级到8.x版本,确保与.NET 8 runtime完全匹配。
  • 修正迁移文件:打开生成的UpdateFieldName迁移文件,检查RenameColumnOperation代码,确认OldName、NewName和table参数都正确赋值,无空值。示例正确代码:
    migrationBuilder.RenameColumn(
        name: "AddressId",
        table: "YourTableName",
        newName: "addressId");
    
  • 重新生成迁移:先移除旧迁移,再重新生成并更新数据库:
    dotnet ef migrations remove
    dotnet ef migrations add UpdateFieldName
    dotnet ef database update
    

内容的提问来源于stack exchange,提问作者Ben

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 09:05:58