0

There is a model:

 namespace WebApi.Entities
    {
        public class Category
        {
            public Category()
            {
                CategoryId = Guid.NewGuid().ToString();
            }
    
            [Key]
            public string CategoryId { get; set; }
            public string Title { get; set; }
            public List<Item> Items { get; set; }
        }
    }

In CategoryService there is a method: AssignItem

    public void AssignItem(string id, Item Item)
    {
        var Category = _context.Categories.Find(id);

        Category.Items.Add(Item);

        _context.Categories.Update(Category);
        _context.SaveChanges();
    }

The arguments in function is:

  • id - used to search the record for a specific id.
  • Item - correct Item model delivered from frontend

I getting the error:

Object reference not set to an instance of an object

in this line: Category.Items.Add(Exercise);

How to fix it - for assign item to specific category?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Piotr Żak
  • 2,046
  • 5
  • 18
  • 30
  • Yes - exactly - this doesn't exist - so need to add in constructor - and List will create when instance of class emergence. Thanks. – Piotr Żak Sep 03 '20 at 16:46

1 Answers1

1

In your constructor, add a line for

public Category()
{
    CategoryId = Guid.NewGuid().ToString();= 
    Items = new List<Item>();
}

Your Items list is currently null.

Carson
  • 864
  • 1
  • 6
  • 19