SkyeBoniwell
SkyeBoniwell

Reputation: 7122

PUT request to API is setting values to NULL

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

Upvotes: 0

Views: 246

Answers (1)

Brando Zhang
Brando Zhang

Reputation: 28322

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

Upvotes: 1

Related Questions