我正在尝试创建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"
}
注意:要求只使用DbContext模型。如有任何解决方案,请提前感谢。
您可以为您的请求使用单独的DTO
,然后从中填充模型,或者如果您想使用相同的模型,您可以将Employee属性设置为internal
或protected
或private
,以便swagger可以忽略它。
这适用于swashbuckle
Swagger
DTO参考
如何配置Swashbuckle忽略模型
上的属性有两种解决方案可以满足您的需求:
Solution1:
修改EmployeeDetails模型中的属性
public virtual Employee? Employee { get; set; }
Solution2:
在您的csproj文件中禁用null验证,如下所示:
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
......
<Nullable>disable</Nullable>
......
</PropertyGroup>