问题描述
有一个模型:
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>();
}
您的项目列表当前为空。