0

I have created a simple api where I would like to edit the object's data using the PUT method. However, I only upload some properties of this object to the API (because I don't edit all the fields). Is it possible for me to download an object with a given id from the database and update only its properties, which are not empty in the submitted object?

Questions (Model)

[Key]
public int QuestionId { get; set; }
public string QuestionContent { get; set; }
public string MediaUrl { get; set; }
public string Description{ get; set; }

API method

[HttpPut]
[Route("{id:int}")]
public Questions Edit(int id, [FromQuery]Questions question)
{
 Questions currentQuestion = _context.Questions.FirstOrDefault(x => x.QuestionId == id);
}

I update object using Postman like this: enter image description here

Now, in this case i send request to the method and i got Question id, Questions object with MediaUrl, QuestionContent, and null as Description.

It is possible update selected Question object (selected using passed id) using passing Question property who not null?

1
  • 5
    It is convention that PUT should update all fields and replace original version of data. PATCH should be used for partial update. You are looking for JsonPatchDocument roundthecode.com/dotnet/asp-net-core-web-api/… Commented Jun 29, 2021 at 17:44

1 Answer 1

3

you can use automapper and try to ignore the null values like the following

CreateMap<Questions, Questions>()
     .ForAllMembers(opts => opts.Condition((src, dest, member) => member != null));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.