Entity Framework .NET 中的字段为必填错误

问题描述 投票:0回答:1
public class Activity
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int ActivityId { get; set; }
    [ForeignKey("Pet")]
    public int PetId { get; set; }
    public Pet Pet { get; set; }
    public string ActivityName { get; set; }
    
}

在我的 .NET API 项目中,我有一个名为 Activity 的模型,我想发送如下的发布请求:

{
  "activityId": 2,
  "petId": 1,
  "activityName": "Walking"
}

但是我收到这样的错误:


{
  "errors": {
    "Pet": [
      "The Pet field is required."
    ]
  },
  "type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "00-706cba6aef91222dac75191c63c25a79-a4263882e7c4407b-00"
}

我想要的是在我的宠物模型和表格中将其记录为列表,如下所示,当我输入petId时:

public class Pet
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int PetId { get; set; }
    public string Type { get; set; }
    public string Name { get; set; }
    public List<Activity> Activities { get; set; } = new List<Activity>();
    public List<Food> Foods { get; set; } = new List<Food>();
}

我应该如何纠正模型,我是初学者,非常感谢您的帮助。

![Topluluk Tarafından Doğrulandı simgesi](数据:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAQAAAAngNWGAAAA/0lEQVR4AYXNMSiEcRyA4cfmGHQbCZIipkuxnJgMStlMNmeyD2dwmc8+sZgxYJd9ErIZFHUyY YD7fkr6l4/rnvmtl7+KitrqV/fq2Y5eLY3Z9S48eRLe7BmVZ9qhTLhQ0algzZWQOVKSsCF8OjAnwbxDTWFDUhPK/jMr1H6HE/IqRky2DyvCefuwItwZzodVoYRiLqMkVCXrwpJ9twZ+sgfDYEFYl8wIW xZ9uFf7zkallxlJh4YrLGsKjZRx7VGHhLqwgFUN45DGdb8MeXGpgB4ABZdeDcpZEY51A+hyLKz4S1W4MQWm3AibWtgWmk6dyISA1pSdyWTOlLXVp0+eL9D/ZPfBTNanAAAAAElFTkSuQmCC)

I am trying to solve the error I get as I explained in my question.
.net entity-framework
1个回答
0
投票

尝试使用 virtual 关键字在导航属性上启用延迟加载:

public virtual List<Activity> Activities { get; set; } = new List<Activity>();
public virtual List<Food> Foods { get; set; } = new List<Food>(); 
© www.soinside.com 2019 - 2024. All rights reserved.