【问题标题】:Entity Framework model as Request Model实体框架模型作为请求模型
【发布时间】:2022-11-13 23:23:39
【问题描述】:

我正在尝试创建 Post API,它具有以下模型作为请求

public partial class Employee
    {
        public Employee()
        {
            EmployeeDetails = new HashSet<EmployeeDetail>();
        }

        public int Id { get; set; }
        public string? Name { get; set; }
        public string? Gender { get; set; }
        public int Age { get; set; }

        public virtual ICollection<EmployeeDetail> EmployeeDetails { get; set; }
    }

 public partial class EmployeeDetail
    {
        public int Id { get; set; }
        public int? EmployeeId { get; set; }
        public string? Details { get; set; }

        public virtual Employee Employee { get; set; }
    }

我有和 Post API 接受参数 EmployeeDetail

public async Task<IActionResult> Post(EmployeeDetail empDetail){
      

}

so for this getting error : 
Bad Request 400.

插入 empDetail 的代码,(假设 Employee 已经存在于数据库中,因此不将任何值与 Employee 对象绑定。并基于 EmployeeId,在 employeeDetail 表中插入 Employee 详细信息。)

This is what swagger suggesting for body request.
{
  "id": 0,
  "employeeId": 0,
  "details": "string",
  "employee": {
    "id": 0,
    "name": "string",
    "gender": "string",
    "age": 0,
    "employeeDetails": [
      "string"
    ]
  }
}

//But I only want to pass 
{ 
  "id": 0,
  "employeeId": 0,
  "details": "string"
}

任何解决方案提前致谢。

【问题讨论】:

    标签: .net entity-framework-core asp.net-core-mvc


    【解决方案1】:

    您可以为您的请求使用单独的DTO,然后从中填充模型或者如果您想使用相同的模型,您可以将 Employee 属性设置为“内部”或“受保护”或“私有”,以便大摇大摆可以忽略它。

    这适用于swashbuckle Swagger

    参考DTO

    How to configure Swashbuckle to ignore property on model

    【讨论】:

      猜你喜欢
      • 2011-07-22
      • 1970-01-01
      • 2012-07-03
      • 2018-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多