Search code examples
.netinstanceedit

Update Model (adding element to List<Model>)


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?


Solution

  • In your constructor, add a line for

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

    Your Items list is currently null.