I am trying to create Post API, which has following Model as request
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; }
}
and I have and Post API which accept in parameter EmployeeDetail
public async Task<IActionResult> Post(EmployeeDetail empDetail){
}
so for this getting error :
Bad Request 400.
Code to insert empDetail,(Let assume Employee already exist in database so not binding any value with Employee object., and based on EmployeeId, inserting Employee detail in employeeDetail table.)
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"
}
Note : Requirement is to use only DbContext Model only. Any solution Thanks in Advance.
CodePudding user response:
You can use a separate DTO
for your request and then fill the model from that Or if you want to use the same model you can set the Employee property as internal
or protected
or private
so the swagger can ignore it.
This is applicable to swashbuckle
Swagger
Reference for DTO
How to configure Swashbuckle to ignore property on model
CodePudding user response:
There're two solutions may meet your requirement:
Solution1:
modify the property in your EmployeeDetails Model
public virtual Employee? Employee { get; set; }
Solution2:
disable the null validation in your csproj file as below:
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
......
<Nullable>disable</Nullable>
......
</PropertyGroup>