Reputation: 7555
I have below Endpoint in ASP.Net Core 2.1
with EF Core 2.1
public class CustomerController
{
public IActionResult Post([FromBody]CustomerTO customer)
{
}
public IActionResult Get(int id)
{
var customer = _dal.GetCustomer(id);
return Ok(customer);
}
}
CustomerTO looks as
public class CustomerTO
{
public int CustomerId { get; set; }
public string CustomerName { get; set; }
//others
}
Now the issue is in Swagger docs, the request payload for POST includes CustomerId: 0
(however optional)
So the consumer of the API passes CustomerId = someInt in the POST request, as its an Identity property in EF Core Dal, it throws the error
Cannot insert value on Identity column...
This error is quite obvious & acceptable,
what is my requirement how do I make Swagger aware that CustomerId is not part of request payload in POST request?
Creating a separate DTO for Get & Post seems an overhead.
Thanks!!
Upvotes: 0
Views: 2613
Reputation: 239290
For this specific scenario, you can simply make the property nullable and then decorate it as follows:
[JsonProperty(NullValueHandling = NullValueHandling.Ignore]
public int? CustomerId { get; set; }
Then, if it has a value, it will be present, otherwise it will not be part of the JSON object.
However, if you find yourself needing to change multiple different properties or adding/removing stuff for the sake of just the request or the response more than this, then @DarjanBogdan is correct: you should just use different classes for each.
Upvotes: 1