【问题标题】:PUT request to API is setting values to NULL对 API 的 PUT 请求将值设置为 NULL
【发布时间】:2021-01-24 15:43:00
【问题描述】:

我在下面有一个执行 PUT 请求的 .Net Core API 控制器。

Sql Server 中受影响的表如下所示:

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

在测试中,我在 PUT API 调用中发送我想要更改的属性:

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

它确实更新了数据库中的条目,但它还将所有未在 PUT 调用中发送的值设置为 NULL。因此,虽然它确实更新了 optionDescription,但它会将除 optionID 之外的所有其他值设置为 NULL。

如何阻止它设置其他值?

谢谢!

这里是控制器:

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

【问题讨论】:

  • 从数据库中获取记录,只修改你想要的字段,保存到数据库?

标签: asp.net-core entity-framework-core asp.net-core-webapi asp.net-core-3.1


【解决方案1】:

根据您的描述,我建议您可以先尝试附加模型,然后将特定属性IsModified设置为true。

这只会更新特定字段,而不是更新整个模型。

更多细节,你可以参考下面的例子:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-19
    • 2021-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多