entity-framework-coreasp.net-core-2.1

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

  • 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;