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

We use to get the following error when we try to run add-migration. We use Entity Framework Core 2.1.

System.NullReferenceException: Object reference not set to an instance of an object. at Microsoft.EntityFrameworkCore.Metadata.Internal.TableMapping.<>c.b__10_0(IEntityType t) at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable1 source, Func2 predicate) at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.GetSortedProperties(TableMapping target) at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.Add(TableMapping target, DiffContext diffContext)+MoveNext() at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.DiffCollection[T](IEnumerable1 sources, IEnumerable1 targets, DiffContext diffContext, Func4 diff, Func3 add, Func3 remove, Func4[] predicates)+MoveNext() at System.Linq.Enumerable.ConcatIterator1.MoveNext() at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.Sort(IEnumerable1 operations, DiffContext diffContext) at Microsoft.EntityFrameworkCore.Migrations.Design.MigrationsScaffolder.ScaffoldMigration(String migrationName, String rootNamespace, String subNamespace, String language) at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType) at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType) at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.b__0() at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action) Object reference not set to an instance of an object.



Solution 1:[1]

The issue for this is a mismatch between DataContextModelSnapshot file and your entity classes. Usually this happen due to merge conflicts in the DataContextModelSnapshot file.

It's very hard to find the mismatch just by going through the history of the DataContextModelSnapshot file. Therefore the easiest solution for this is to;

  • Delete the Snapshot file.
  • Run Add-Migration 'Migration_Name' (This is going to create the snapshot file from the scratch and also create a new Migration file).
  • Delete the Newly Created Migration file manually.
  • Now you can start adding Add-Migration for the new changes.

Solution 2:[2]

I had a similar issue but found it was because I named a previous migration DateOnly

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tharindu Jayasinghe
Solution 2 Davious