1

On My DB context class I have code like this

  modelBuilder.Entity("WebApplication10.Data.JobCategory", b =>
            {
                b.Property<int>("ID")
                    .ValueGeneratedOnAdd();

                b.Property<string>("JobCategoryName");

                b.Property<int>("JobCategoryParentID");

                b.Property<string>("jobCategoryDetails");

                b.HasKey("ID");

                b.ToTable("JobCategory");
            });

And on my controller

 private readonly ApplicationDbContext _context;

    public IActionResult Index()
    {
        return View( _context.JobCategory.ToList());
    }

but on my controller class I get an error like this

An exception of type 'System.NullReferenceException' occurred in WebApplication10.dll but was not handled in user code

Additional information: Object reference not set to an instance of an object. Can anyone point out what i am doing wrong?

None
  • 5,582
  • 21
  • 85
  • 170

1 Answers1

1

It seems like your _context variable has never been initialized so how can you access its JobCategory property?

The runtime throwing a NullReferenceException always means the same thing: you are trying to use a reference. The reference is not initialized (or it was initialized, but is no longer initialized).

This means the reference is null, and you cannot access members through a null reference. The simplest case:

string foo = null;
foo.ToUpper();

This will throw a NullReferenceException at the second line, because you can't call the instance method ToUpper() on a string reference pointing to null.

Initial your variable like this:

private readonly ApplicationDbContext _context = new ApplicationDbContext();
user3378165
  • 6,546
  • 17
  • 62
  • 101