更新模型将元素添加到List <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; }
        }
    }

在CategoryService中,有一种方法:AssignItem

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

        Category.Items.Add(Item);

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

函数中的参数为:

  • id -用于在记录中搜索特定ID。
  • Item -前端提供的正确商品模型

我得到了错误:

对象引用未设置为对象的实例

在此行:Category.Items.Add(Exercise);

如何解决-将项目分配到特定类别?

解决方法

在构造函数中,添加一行

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

您的项目列表当前为空。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...