【问题标题】:Entity Framework Core 2.1 Add Migration System.NullReferenceException: Object reference not set to an instance of an objectEntity Framework Core 2.1 添加迁移 System.NullReferenceException:对象引用未设置为对象的实例
【发布时间】:2022-04-19 02:31:31
【问题描述】:

当我们尝试运行 add-migration 时,我们会收到以下错误。 我们使用 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(TableMapping 目标) 在 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(字符串名称,字符串 outputDir,字符串 contextType) 在 Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(字符串名称,字符串 outputDir,字符串 contextType) 在 Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.c__DisplayClass3_0`1.b__0() 在 Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(操作动作) 对象引用未设置为对象的实例。

【问题讨论】:

    标签: entity-framework-core asp.net-core-2.1


    【解决方案1】:

    问题在于 DataContextModelSnapshot 文件与您的实体类不匹配。这通常是由于 DataContextModelSnapshot 文件中的合并冲突而发生的。

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

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-06-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-03
        • 2021-07-10
        相关资源
        最近更新 更多