question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Add-Migration NullReferenceException

See original GitHub issue

The database context generated by Scaffold-DbContext. After generating the context I moved all entity configurations in OnModelCreating to separate config file implementing IEntityTypeConfiguration<T>. OnModelCreating is like this now.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
      modelBuilder.ApplyConfigurationsFromAssembly(GetType().Assembly);
}

The same setup is working in EF Core v2.2.6.

Steps to reproduce

Add-Migration IntitialSchema

StackTrace

DesignTimeDbContextFactoryBase.BasePath: D:\Working_Projects
DesignTimeDbContextFactoryBase.Create(string): Connection string: 'Server=DW;Database=DeveDB;Trusted_Connection=True;Application Name=Portal;'.
DbContext Assembly: Portal.Persistence, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.EntityFrameworkCore.Design.Internal.CSharpHelper.Literal(String value)
   at Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationOperationGenerator.Generate(CreateTableOperation operation, IndentedStringBuilder builder)
   at Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationOperationGenerator.Generate(String builderName, IReadOnlyList`1 operations, IndentedStringBuilder builder)
   at Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGenerator.GenerateMigration(String migrationNamespace, String migrationName, IReadOnlyList`1 upOperations, IReadOnlyList`1 downOperations)
   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.AddMigration.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Object reference not set to an instance of an object.

Further technical details

EF Core version: 3.0.0-rc1.19456.14 Database provider: Microsoft.EntityFrameworkCore.SqlServer (3.0.0-rc1.19456.14) Target framework: .NET Core 3.0 SDK: .NET Core 3.0rc1 Operating system: Windows 10 IDE: Visual Studio 2019 16.2.5

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:1
  • Comments:9 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
hannan-mcommented, Sep 19, 2019

Yes, it’s related to #17474.

Steps to reproduce.

Create a database

CREATE DATABASE [Blogging];
GO

USE [Blogging];
GO

CREATE TABLE [Blog] (
    [BlogId] int NOT NULL IDENTITY,
    [Url] nvarchar(max) NOT NULL,
    CONSTRAINT [PK_Blog] PRIMARY KEY ([BlogId])
);
GO

CREATE TABLE [Post] (
    [PostId] int NOT NULL IDENTITY,
    [BlogId] int NOT NULL,
    [Content] nvarchar(max),
    [Title] nvarchar(max),
    CONSTRAINT [PK_Post] PRIMARY KEY ([PostId]),
    CONSTRAINT [FK_Post_Blog_BlogId] FOREIGN KEY ([BlogId]) REFERENCES [Blog] ([BlogId]) ON DELETE CASCADE
);
GO

INSERT INTO [Blog] (Url) VALUES
('http://blogs.msdn.com/dotnet'),
('http://blogs.msdn.com/webdev'),
('http://blogs.msdn.com/visualstudio')
GO

Scaffold DbContext

Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

Create the following models

public class Author
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    public class AuthorPost
    {
        public int AuthorId { get; set; }
        public ICollection<Post> Posts { get; set; }

        public virtual Author Author { get; set; }
    }

DbContext and entity configurations

public partial class BloggingContext : DbContext
    {
        public BloggingContext()
        {
        }

        public BloggingContext(DbContextOptions<BloggingContext> options)
            : base(options)
        {
        }

        public virtual DbSet<Blog> Blog { get; set; }
        public virtual DbSet<Post> Post { get; set; }
        public virtual DbSet<Author> Authors { get; set; }
        public virtual DbSet<AuthorPost> AuthorPosts { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlServer("Server=DW;Database=Blogging;Trusted_Connection=True;");
            }
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.ApplyConfigurationsFromAssembly(GetType().Assembly);
        }
    }

    public class BlogConfiguration : IEntityTypeConfiguration<Blog>
    {
        public void Configure(EntityTypeBuilder<Blog> builder)
        {
            builder.Property(e => e.Url).IsRequired();
        }
    }

    public class AuthorConfiguration : IEntityTypeConfiguration<Author>
    {
        public void Configure(EntityTypeBuilder<Author> builder)
        {
            // remove .HasComment("Author fullname") and then run Add-Migration. It will work.
            builder.Property(e => e.Name).IsRequired().HasComment("Author fullname");
        }
    }

    public class AuthorPostConfiguration : IEntityTypeConfiguration<AuthorPost>
    {
        public void Configure(EntityTypeBuilder<AuthorPost> builder)
        {
            builder.HasNoKey();
        }
    }

    public class PostConfiguration : IEntityTypeConfiguration<Post>
    {
        public void Configure(EntityTypeBuilder<Post> builder)
        {
            builder.HasOne(d => d.Blog)
                .WithMany(p => p.Post)
                .HasForeignKey(d => d.BlogId);
        }
    }

Now run

Add-Migration CreateAuthorAndPostRelation

Stacktrace

System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.EntityFrameworkCore.Design.Internal.CSharpHelper.Literal(String value)
   at Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationOperationGenerator.Generate(CreateTableOperation operation, IndentedStringBuilder builder)
   at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid3[T0,T1,T2](CallSite site, T0 arg0, T1 arg1, T2 arg2)
   at Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationOperationGenerator.Generate(String builderName, IReadOnlyList`1 operations, IndentedStringBuilder builder)
   at Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGenerator.GenerateMigration(String migrationNamespace, String migrationName, IReadOnlyList`1 upOperations, IReadOnlyList`1 downOperations)
   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.AddMigration.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Object reference not set to an instance of an object.

If we remove .HasComment("Author fullname") migration will add successfully.

0reactions
ajcvickerscommented, Apr 1, 2020

@404Prachi You need to update to ASP.NET Core 3.1 and EF Core 3.1.

Read more comments on GitHub >

github_iconTop Results From Across the Web

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 ...
Read more >
Object reference not set to an instance of an object.
and run dotnet ef migrations it'll work fine. The problem is with the current main branch while mapping the passenger entity.
Read more >
FIX: Object reference not set to an instance of object Add- ...
Quick fix for System.NullReferenceException: Object reference not set to an instance of an object · Open Solution Explorer in Visual Studio & go ......
Read more >
Add-Migration NullReferenceException #6389
Hi, I try to add migration to EF and get null pointer exception How can I debug the process? PM> Add-Migration "Added_xxx" -Context ......
Read more >
Why "System.NullReferenceException " is occurred in ...
It simply means that some member/variable of some reference type is dereferenced by using and of its instance (non-static) members, which ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found