0

I have this .Net Core API controller below that does a PUT request.

The table affected in Sql Server, looks like this:

carID  (varchar(15), NULL)
optionID (varchar(15), NOT NULL)
optionDescription (varchar(255), NULL)
optionType (varchar(50), NULL)
factoryID (varchar(15), NULL)

In testing, I am sending along the properties I want changed like this in my PUT API call:

{
    " optionID": "633fr",
    "optionDescription": "Full Tech Package A"
}

It does update the entry in the database, but it's also setting all the values not sent in the PUT call to NULL. So while it does update optionDescription, it is setting all the other values to NULL except optionID.

How do I stop it from setting the other values?

thanks!

Here is the controller:

    // PUT: api/CarOptions/5
    [HttpPut("{id}")]
    public async Task<IActionResult> PutCarOptions(Guid id, CarOptions carOptions)
    {
        if (id != carOptions.OptionId)
        {
            return BadRequest();
        }

        _context.Entry(carOptions).State = EntityState.Modified;

        try
        {
            await _context.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!CarOptionsExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return NoContent();
    }
1
  • 1
    Get the record from database, modify only the fields you want to, save to database? Commented Oct 9, 2020 at 14:39

1 Answer 1

1

According to your description, I suggest you could try to attach the model firstly and then set the specific property IsModified to true.

This will only update specific fields instead of updating whole model.

More details, you could refer to below example:

    // PUT: api/CarOptions/5
    [HttpPut("{id}")]
    public async Task<IActionResult> PutCarOptions(Guid id, CarOptions carOptions)
    {
        _context.Documents.Attach(carOptions);
        _context.Entry(carOptions).Property(x => x.optionDescription).IsModified = true;
        _context.SaveChanges();


        return NoContent();
    }
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.