Entity Framework 核心 2.1 添加迁移 System.NullReferenceException:对象引用未设置为对象的实例

Entity Framework Core 2.1 Add Migration System.NullReferenceException: Object reference not set to an instance of an object

我们在尝试 运行 添加迁移时经常遇到以下错误。 我们使用 Entity Framework Core 2.1.

System.NullReferenceException: 对象引用未设置为对象的实例。 在 Microsoft.EntityFrameworkCore.Metadata.Internal.TableMapping.<>c.b__10_0(IEntityType t) 在 System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable1 source, Func2 谓词) 在 Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.GetSortedProperties(表映射目标) 在 Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.Add(TableMapping 目标,DiffContext diffContext)+MoveNext() 在 Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.DiffCollection[T](IEnumerable1 sources, IEnumerable1 目标,DiffContext diffContext,Func4 diff, Func3 添加,Func3 remove, Func4[] 谓词)+MoveNext() 在 System.Linq.Enumerable.ConcatIterator1.MoveNext() at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.Sort(IEnumerable1 次操作中,DiffContext diffContext) 在 Microsoft.EntityFrameworkCore.Migrations.Design.MigrationsScaffolder.ScaffoldMigration(字符串迁移名称、字符串根命名空间、字符串子命名空间、字符串语言) 在 Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(字符串名称、字符串输出目录、字符串上下文类型) 在 Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(字符串名称、字符串输出目录、字符串上下文类型) 在 Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.b__0() 在 Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(动作动作) 对象引用未设置为对象的实例。

此问题是 DataContextModelSnapshot 文件与您的实体不匹配 类。这通常是由于 DataContextModelSnapshot 文件中的合并冲突造成的。

仅通过浏览 DataContextModelSnapshot 文件的历史记录很难找到不匹配的地方。 因此,最简单的解决方案是;

  • 删除快照文件。
  • 运行 Add-Migration 'Migration_Name'(这是 从头开始创建快照文件并创建一个 新迁移文件)。
  • 删除新创建的迁移文件 手动。
  • 现在您可以开始添加 Add-Migration 以进行新更改。

我遇到了类似的问题,但发现这是因为我将之前的迁移命名为 DateOnly

https://github.com/dotnet/efcore/issues/26954